循环 目标 区分不同类型的循环。 记住每种循环类型的语法。 使用 或 修改循环的执行。 引言 循环是编程语句,允许代码段在满足条件时重复执行。 流程图显示了循环的过程。 来源:DotNetTutorials C# 中有三种不同的循环类型: 循环 循环 循环 While 循环 while 循环在给定条件为真时执行一段代码块,这个条件会在执行代码块之前进行测试。 以下是一个 循环的语法: 一旦条件被测试并且结果为假,循环体将被跳过,并且程序将继续执行循环之后的内容。 下面是一个从数字 开始倒计数的 循环示例。 For 循环 与 while 循环不同,where 的执行次数不一定已知,而 for 循环总是知道需要执行其内容的次数。 也就是说, 循环有一个定义好的重复次数。
break 或 continue 修改循环的执行。循环是编程语句,允许代码段在满足条件时重复执行。

C# 中有三种不同的循环类型:
while 循环for 循环do while 循环while 循环在给定条件为真时执行一段代码块,这个条件会在执行代码块之前进行测试。
以下是一个 while 循环的语法:
while (condition) { //Code to be executed for as long as condition remains true. }
一旦条件被测试并且结果为假,循环体将被跳过,并且程序将继续执行循环之后的内容。
下面是一个从数字 5 开始倒计数的 while 循环示例。
int num = 5; Console.WriteLine("Let the countdown begin! 5..."); while (num > 0) { num--; Console.WriteLine(num); }
与 while 循环不同,where 的执行次数不一定已知,而 for 循环总是知道需要执行其内容的次数。
也就是说,for 循环有一个定义好的重复次数。
以下是一个 for 循环的语法:
//In C#, a for loop is declared with an initial value, a condition that said value must meet and an increase value by which the initial value is increased every run of the loop. for ( initial value; condition; increase ) { //Code to be executed until condition is met. }
初始值和增量值通常是数值的,条件通常是比较增加的值与目标值。
下面是一个输出 0 to 5 范围内数字的 for 循环示例。
for (int i = 0; i < 5; i++) { Console.WriteLine(i); }
Do...while 循环类似于 while 循环,不同之处在于循环将在循环末尾检查条件,而不是在开始时。这确保了代码块至少执行一次。
以下是一个 do...while 循环的语法:
do { //Code to be executed } while (condition);
如果条件为真,则循环将回到 do after running, and executes its body again. This process will repeat until the condition is tested and results in false.
Provided below is an example of a do...while loop that outputs a value i starting at 0 so long as i is less than 5。
int i = 0; do { Console.WriteLine(i); i++; } while (i < 5);
然而,也有一些语句允许我们在初始条件的情况下控制或改变循环的执行。
在 C# 中我们可以使用:
break which terminates the loop (or switch) statement.continue which causes the loop to skip part of its body and retest the condition before moving on.Provided below is an example of using a break statement to terminate a loop when the value of i is equal to 5。
for (int i = 0; i < 10; i++) { if (i == 5) { break; } Console.WriteLine(i); }
下面是一个使用 continue statement to skip the iteration for when the value of i is 5 的示例。
for (int i = 0; i < 10; i++) { if (i == 5) { continue; } Console.WriteLine(i); }
需要注意的一个因素是循环可能变成无限循环。无限循环 发生在一个预先设定的条件永远不会变为假的情况。虽然这听起来像是一个错误,但在某些情况下可以使用连续的无限循环!
以下是两个示例:
while(true) { }
由于条件不是一个变量而是布尔值 true,这个 while 循环将永远不停止运行。
for ( ; ; ) { }
将 for 循环的条件表达式留空会导致计算机认为它们为真,并将持续执行。
我们已经确定了以下资源来提供本课中所学内容的更多背景和学习材料。我们鼓励您复习下面的材料并探索其他相关主题。
声明:
本文件灏天文库团队进行了翻译。尽管我们力求准确,但请注意,翻译可能包含错误或不准确之处。原文档以其原始语言为准。我们不对因使用此翻译而产生的任何误解或误译负责。