我們如何在 C# 的 while 迴圈中使用 break 語句?
break 語句終止迴圈並將執行權轉到緊跟該迴圈後的語句。
當在迴圈內遇到 break 語句時,該迴圈將立即終止,並且程式控制將恢復到緊跟該迴圈後的下一個語句。
我們來看看一個示例以瞭解如何在 while 迴圈中使用 break 語句。以下程式碼片段使用 break 語句終止迴圈。
if (a > 15) { break; }
以下為完整程式碼。
示例
using System; namespace Demo { class Program { static void Main(string[] args) { /* local variable definition */ int a = 10; /* while loop execution */ while (a < 20) { Console.WriteLine("value of a: {0}", a); a++; if (a > 15) { /* terminate the loop using break statement */ break; } } Console.ReadLine(); } } }
輸出
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15
廣告