C# For 循环
示例
ForLoop非常适合在一定时间范围内执行操作。这就像一个While循环,但增量包含在条件中。
这样设置一个For循环:
for (Initialization; Condition; Increment) { // 码 }
初始化-生成只能在循环中使用的新局部变量。
条件-仅当条件为true时,循环才会运行。
增量-变量在每次循环运行时如何变化。
一个例子:
for (int i = 0; i < 5; i++) { Console.WriteLine(i); }
输出:
0
1
2
3
4
您也可以在For循环中保留空格,但是必须具有所有分号才能使其起作用。
int input = Console.ReadLine(); for ( ; input < 10; input + 2) { Console.WriteLine(input); }
输出为3:
3
5
7
9
11