C#支持哪些类型的循环?
循环语句使我们可以多次执行一条语句或一组语句。以下是C#支持的循环-
在给定条件为true时,它重复一个语句或一组语句。它在执行循环体之前测试条件。
它多次执行一系列语句,并简化了管理循环变量的代码。
它类似于while语句,不同之处在于它在循环主体的末尾测试条件
使用C#,您还可以如下所示使用foreach循环-
示例
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int [] n = new int[10]; /* n is an array of 10 integers */
/* initialize elements of array n */
for ( int i = 0; i < 10; i++ ) {
n[i] = i + 100;
}
/* output each array element's value */
foreach (int j in n ) {
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}输出结果
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109