C# do...while 迴圈

C# 迴圈 C# 迴圈

不像 forwhile 迴圈,它們是在迴圈頭部測試迴圈條件。do...while 迴圈是在迴圈的尾部檢查它的條件。

do...while 迴圈與 while 迴圈類似,但是 do...while 迴圈會確保至少執行一次迴圈。

語法

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

do
{
   statement(s);

}while( condition );

請注意,條件運算式出現在迴圈的尾部,所以迴圈中的 statement(s) 會在條件被測試之前至少執行一次。

如果條件為真,控制流會跳轉回上面的 do,然後重新執行迴圈中的 statement(s)。這個過程會不斷重複,直到給定條件變為假為止。

流程圖

C# 中的 do...while 迴圈

實例

實例

using System;

namespace Loops
{
   
    class Program
    {
        static void Main(string[] args)
        {
            /* 局部變數定義 */
            int a = 10;

            /* do 迴圈執行 */
            do
            {
               Console.WriteLine("a 的值: {0}", a);
                a = a + 1;
            } while (a < 20);

            Console.ReadLine();
        }
    }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
a 的值: 16
a 的值: 17
a 的值: 18
a 的值: 19

C# 迴圈 C# 迴圈