C# do...while loop

C# loops

UnlikeforandwhileLoops test the loop condition at the top of the loop.do...whileThe loop checks its condition at the bottom of the loop.

do...whileThe loop is similar to the while loop, but the do...while loop ensures that the loop is executed at least once.

Syntax

In C#do...whileThe syntax of loops:

do
{
   statement(s);

}while( condition );

Note that the conditional expression appears at the bottom of the loop, so the statement(s) in the loop are executed at least once before the condition is tested.

If the condition is true, the control flow jumps back to the do above, and then re-executes the statement(s) in the loop. This process repeats continuously until the given condition becomes false.

Flowchart

C# 中的 do...while 循环

Example

Example

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();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

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

C# loops

other extensions