Skip to content
On this page

do…while 循环

C#中, do...while 循环也是一种常用的循环结构。循环结构各部分运行顺序如下:

img

从上面的示意可以看出, do...while 循环第一次执行循环体是没有经过条件判断的,也就是说会无条件的执行一次循环体,此后的逻辑顺序就与 while 循环相同了——先判断条件,条件为 true 再执行循环体一次。请看下面的例子:

img

尽管循环条件始终为 false ,但由于 do...while 循环第一次执行循环体不判断条件,所以循环体还是执行了一次。运行结果为:

img

我们已经学习了 C#中最常用的三种循环结构,下面我们小小总结一下:

img

任务

右边代码只能打印一个数字,请修改第 11 行变量 x 的初始值,使程序能够输出 3 个数字。

代码

csharp
using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 2; 
            do
            {
                x ++;
                Console.Write(x + " ");
            }
            while(x > 2 && x <= 4);
        }
    }
}

编程练习

for 循环的特点,是把与循环有关的内容都放在 (计数变量初始化;循环条件;变量自加) 里面,使得程序结构清楚,适合于已知循环次数的循环。

练习:请在第 11 行完善 for 循环结构,使得程序能够打印 6 行“Yeah! ”

csharp
using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 6; ++i) //请填写 for 循环结构 
            {
                Console.WriteLine("Yeah!");
            }
        }
    }
}