The do operator iterates over a block of code until a conditional query equals false. The do-while loop can also be interrupted by a goto
, return
, break
or throw
statement.
The syntax for the do
keyword is:
do { code block; } while( condition );
Example:
int i = 0;
do
{
Console.WriteLine("Do is on loop number {0}.", i);
} while (i++ < 5);
Output:
"Do is on loop number 1."
"Do is on loop number 2."
"Do is on loop number 3."
"Do is on loop number 4."
"Do is on loop number 5."
Unlike the while
loop, the do-while loop is Exit Controlled. This means that the do-while loop would execute its statements at least once, even if the condition fails the first time.
bool a = false;
do
{
Console.WriteLine("This will be printed once, even if a is false.");
} while (a == true);