首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 迴圈語句完全掌握:for、while、do-while 與 foreach 實戰

     編輯:關於C#

迴圈:讓程式碼重複執行的利器

迴圈讓相同邏輯重複執行成千上萬次,C# 提供四種迴圈:for、while、do-while、foreach。

一、for 迴圈

適用於已知迴圈次數的情境。

for (int i = 1; i <= 7; i++)
{
    Console.WriteLine("編程bianceng");
}

for 迴圈輸出結果

執行流程

  1. 初始化 int i = 1(僅執行一次)
  2. 判斷條件 i <= 7,成立則執行迴圈主體
  3. 執行完主體後執行 i++
  4. 回到步驟 2,直到條件不成立結束

變體寫法

int x = 7;
for (; x >= 0; x--)
{
    Console.Write(x);
    Console.WriteLine("編程bianceng");
}

遞減 for 迴圈結果

⚠️ 避免無限迴圈

確保迴圈變數在主體中會改變,否則會陷入死循環,需強制關閉控制台。

二、while 與 do-while 迴圈

while:先判斷後執行

int count = 1;
while (count < 7)
{
    Console.WriteLine("while count = {0}", count);
    count++;
}

do-while:先執行後判斷(至少執行一次)

count = 7;
do
{
    Console.WriteLine("do-while count = {0}", count);
    count--;
} while (count > 0);

while 迴圈結果 do-while 迴圈結果

關鍵差異

  • while:條件不成立時零次執行。
  • do-while:無條件執行第一次,再判斷是否繼續。

三、foreach 迴圈

專為遍歷集合(陣列、List、實作 IEnumerable 的物件)設計,語法簡潔,不需管理索引。

遍歷整數陣列

int[] fib = { 0, 1, 2, 3, 5, 8, 13 };
foreach (int n in fib)
    Console.WriteLine(n);

foreach 整數陣列結果

遍歷字串陣列

string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
foreach (string day in days)
    Console.WriteLine(day);

foreach 字串陣列結果

後續將介紹跳出迴圈的 break、continue、return 用法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved