C# do...while迴圈

不同於for迴圈,以及while迴圈在迴圈開始時測試迴圈條件,do...while迴圈在迴圈結束時檢查其條件。

do...while迴圈類似於while迴圈,唯一的區別是do...while迴圈保證至少執行一次循環體中的代碼塊。

語法

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

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

請注意,條件運算式(condition)放置在迴圈的末尾,因此循環體中的語句在判斷測試條件之前就已經執行了一次。

如果條件(condition)為真,則控制流程將重新開始執行,循環體中的語句將再次執行。重複該過程,直到給定條件變為假。

流程圖

實例代碼

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

上一篇: C#迴圈 下一篇: C#封裝