一、簡介
只要給定條件為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();
}
}
}
輸出結果

