不同于for
循环,以及while
循环在循环开始时测试循环条件,do...while
循环在循环结束时检查其条件。
do...while
循环类似于while
循环,唯一的区别是do...while
循环保证至少执行一次循环体中的代码块。
语法
C# 中的do...while
循环的语法是:
do
{
statement(s);
}while( condition );
请注意,条件表达式(condition
)放置在循环的末尾,因此循环体中的语句在判断测试条件之前就已经执行了一次。
如果条件(condition
)为真,则控制流程将重新开始执行,循环体中的语句将再次执行。重复该过程,直到给定条件变为假。
流程图
实例代码
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
Console.WriteLine("value of a: {0}", a);
a = a + 1;
}while (a < 20);
Console.ReadLine();
}
}
}
当编译和执行上述代码时,会产生以下结果:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19