Skip to content
On this page

循环流程图和 while 循环

程序连续的重复一个步骤称为“循环”。循环可以简化我们的代码,减少冗余。例如,打印 1-10 的整数,我们可以写 10 条打印语句,也可以这样:

img

这个循环结构,会首先判断 x<=10,条件为真时执行循环体(“输出 x”和“x++”),之后,再次判断条件 x<=10,若条件为真则继续执行循环体......若条件为假,则结束循环。

简单的说,

  • 循环是由循环体(需要重复执行的命令)和循环条件组成的。
  • 运行时,先判断循环条件,若条件为 true,就执行循环体一次,然后再判断条件...当条件为 false 时,结束循环

上面的流程图,当变量 x 累加到 11 时,循环条件为 false ,循环就会结束。

C#中,可以用 while 循环结构来实现:

img

对比代码和流程图可知, while 循环结构中,循环条件写在 () 中,循环体写在 {} 中。运行结果:

img

任务

右边的程序是要打印“5 4 3 2 1”,

代码

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

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int y = 5; 
            while (y > 0) //请输入
            {
                Console.Write(y + " ");
                --y; //请输入
            }
        }
    }
}

编程练习

while 循环通常有一个计数变量,循环开始前声明并初始化这个变量;需要有循环条件,当条件为 true 时,执行一次循环体,当条件为 false 时,结束循环。

循环体里面需要有技术变量的自加语句,否则循环可能无法退出(即“死循环”)。

练习:这段程序循环打印 5 次“加油!”,请完善行 ①-③ 的代码。

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

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int x; //循环计数变量 
            x = 0; //行① 请填写计数变量的初始化语句

            while (x < 5) //行② 请填写循环条件
            {
                Console.Write("加油!");
                //行③ 请填写计数变量的自加语句
                ++ x;
            }
        }
    }
}