循環(huán)結(jié)構(gòu)用于對一組命令執(zhí)行一定的次數(shù)或反復(fù)執(zhí)行一組命令,直到指定的條件為假。
(1)while循環(huán)
語法:
while (條件)
{
// 語句
}
功能:只要條件為真,則執(zhí)行循環(huán)體中的語句。
說明:可利用break和continue來控制循環(huán)
(2) do-while循環(huán)
語法:
do
{
// 語句
} while (條件)
功能:與while類似,但有區(qū)別:do…while 循環(huán)中即使條件為假時也至少執(zhí)行一次該循環(huán)體中的語句
(3) for循環(huán)
語法:
for (初始值; 條件; 增/減)
{
//語句
}
說明:
引例:要求對班上的每個學(xué)生統(tǒng)計一個總評。
語法:
foreach (數(shù)據(jù)類型 元素(變量) in 集合或者數(shù)組)
{
//語句
}
說明:用于遍歷整個集合或數(shù)組
舉例:
static void Main(string[] args)
{
// 存放字母的個數(shù)
int countLetters = 0;
// 存放數(shù)字的個數(shù)
int countDigits = 0;
// 存放標(biāo)點符號的個數(shù)
int countPunctuations = 0;
// 用戶提供的輸入
string input;
Console.WriteLine("請輸入一個字符串 ");
input = Console.ReadLine();
// 聲明 foreach 循環(huán)以遍歷輸入的字符串中的每個字符。
foreach(char chr in input)
{
// 檢查字母
if(char.IsLetter(chr))
countLetters++;
// 檢查數(shù)字
if(char.IsDigit(chr))
countDigits++;
// 檢查標(biāo)點符號
if(char.IsPunctuation(chr))
countPunctuations++;
}
Console.WriteLine(“字母的個數(shù)為: {0}", countLetters);
Console.WriteLine(“數(shù)字的個數(shù)為: {0}", countDigits);
Console.WriteLine(“標(biāo)點符號的個數(shù)為: {0}", countPunctuations);
}
|
新聞熱點
疑難解答
圖片精選