C# while循环

一、简介

只要给定条件为true,C#的while循环语句会循环重新执行一个目标的语句。

二、语法

C# while的语法:

while(循环条件)

{  

   循环体;

}

三、执行过程

程序运行到while处,首先判断while所带的小括号内的循环条件是否成立,如果成立的话,也就是返回一个true,则执行循环体,执行完一遍循环体后,再次回到循环条件进行判断,如果依然成立,则继续执行循环体,如果不成立,则跳出while循环体。

在while循环当中,一般总会有那么一行代码,能够改变循环条件,使之终有一天不在成立,如果没有那么一行代码能够改变循环条件,也就是循环体条件永远成立,则我们将称之为死循环。

最简单死循环:

while(true)

{

}

四、特点

先判断,在执行,有可能一遍都不执行。

五、实例

1.向控制台打印100遍,下次考试我一定要细心.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Loops
{
    class Program
    {
        static void Main(string[] args)
        {
            //需要定义一个循环变量用来记录循环的次数,每循环一次,循环变量应该自身加1
            int i = 1;
            while (i<=100)
            {
                Console.WriteLine("下次考试我一定要细心\t{0}", i);
                //每循环一次,都呀自身加-,否则是死循环
                i++; 
            }
            Console.ReadKey();

        }
    }
}

输出结果

 

2.求1-100之间所有整数的和

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Loops
{
    class Program
    {
        static void Main(string[] args)
        {
            //求1-100之间所有整数的和
            //循环体:累加的过程
            //循环条件:i<=100
            int i = 1;
            int sum = 0; //声明一个变量用来存储总和
            while (i<=100)
            {
                sum += i;
                i++;
            }
            Console.WriteLine("1-100之间所有整数的和为{0}",sum);
            Console.ReadKey();


        }
    }
}

输出结果 

 

posted @ 2019-10-25 12:07  笑笑未来  阅读(14593)  评论(0编辑  收藏  举报