C# - Do...While迴圈



不像forwhile迴圈那樣在迴圈開始時測試迴圈條件,do...while迴圈在迴圈結束時檢查其條件。

do...while迴圈類似於while迴圈,不同之處在於do...while迴圈保證至少執行一次。

語法

C#中do...while迴圈的語法如下:

do {
   statement(s);
} while( condition );

請注意,條件表示式出現在迴圈的末尾,因此迴圈中的語句會在條件被測試之前執行一次。

如果條件為真,控制流跳轉回do,迴圈中的語句再次執行。這個過程重複,直到給定的條件變為假。

流程圖

do...while loop in C#

示例

using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;
         
         /* do loop execution */
         do {
            Console.WriteLine("value of a: {0}", a);
            a = a + 1;
         } 
         while (a < 20);
         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
value of a: 16
value of a: 17
value of a: 18
value of a: 19
csharp_loops.htm
廣告