Article

do while Loop


The do-while loop statement executes a statement or a block of statements while a specified Boolean expression evaluates to true. Because that expression is evaluated after each execution of the loop, a do-while loop executes one or more times.The do-while loop stops execution exits when a boolean condition evaluates to false. Because the while(condition) specified at the end of the block, it certainly executes the code block at least once.This differs from the while loop, which executes zero or more times. The do-while loop is the same as the while loop except that it executes the code block at least once.

The syntax of a do-while loop in C# is
do {
   statement(s);
} while( condition );

See a simple example of C# do-while loop to print the table of 2.

using System;
					
public class Program
{
	public static void Main()
	{
		int i = 1;
		int m = 2;

		do
		{
			Console.WriteLine(m + "*" + i + "- " + m*i);
			i++;
		} 
		while (i <= 10);
	}
}

Output

2*1- 2
2*2- 4
2*3- 6
2*4- 8
2*5- 10
2*6- 12
2*7- 14
2*8- 16
2*9- 18
2*10- 20

See a simple example of C# do-while loop to print number 1-10

 using System;
					
public class Program
{
	public static void Main()
	{
	 /* local variable definition */
         int a = 1;
         
         /* do loop execution */
         do {
            Console.WriteLine("value of a is : {0}", a);
            a++;
         } 
         while (a <= 10);
         Console.ReadLine();
      }
}

Output

 
value of a is : 1
value of a is : 2
value of a is : 3
value of a is : 4
value of a is : 5
value of a is : 6
value of a is : 7
value of a is : 8
value of a is : 9
value of a is : 10