迴圈讓相同邏輯重複執行成千上萬次,C# 提供四種迴圈:for、while、do-while、foreach。
適用於已知迴圈次數的情境。
for (int i = 1; i <= 7; i++)
{
Console.WriteLine("編程bianceng");
}

int i = 1(僅執行一次)i <= 7,成立則執行迴圈主體i++int x = 7;
for (; x >= 0; x--)
{
Console.Write(x);
Console.WriteLine("編程bianceng");
}

確保迴圈變數在主體中會改變,否則會陷入死循環,需強制關閉控制台。
int count = 1;
while (count < 7)
{
Console.WriteLine("while count = {0}", count);
count++;
}
count = 7;
do
{
Console.WriteLine("do-while count = {0}", count);
count--;
} while (count > 0);

while:條件不成立時零次執行。do-while:無條件執行第一次,再判斷是否繼續。專為遍歷集合(陣列、List、實作 IEnumerable 的物件)設計,語法簡潔,不需管理索引。
int[] fib = { 0, 1, 2, 3, 5, 8, 13 };
foreach (int n in fib)
Console.WriteLine(n);

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

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