C# do...while Loop
Unlike for and while loops, which test the loop condition at the start, the do...while loop checks its condition at the end of the loop.
The do...while loop is similar to the while loop, but the do...while loop ensures that the loop is executed at least once.
Syntax
The syntax for the do...while loop in C#:
do
{
statement(s);
} while (condition);
Note that the condition expression appears at the end of the loop, so the statement(s) within the loop are executed at least once before the condition is tested.
If the condition is true, the control flow jumps back up to the do, and the statement(s) in the loop are executed again. This process repeats until the given condition becomes false.
Flowchart
Example
Example
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* Local variable declaration */
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 result:
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