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