C # do…while loop
Not like for
and while
loops, they test the loop conditions at the loop header. do...while
a loop checks its condition at the end of the loop.
Do…while cycle vs. while
loop is similar, but do...while
loop ensures that the loop is executed at least once.
Grammar
In C # do...while
syntax of the loop:
do
{
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s)
will be executed at least once before the conditions tested.
If the condition is true, the control flow will jump back to the above do
and then re-execute the statement(s)
. This process is repeated until the given condition becomes false.
Flow chart
C # flow chart
Example
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* Definition of Local Variables */
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:
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