Do while loop

'do while' loop is similar to while loop with only one difference that it checks the condition at the end of the loop. So in this loop at least one time the statement(s) of the loop will be executed even if the condition is false for the first time because it’s checked at the end of the loop.
Let’s try to understand with an example:


void dowhileloopDemo()
{
   int i = 1;
   do
   {
      Console.WriteLine("www.dotnetustad.com");
      i++;
   }
   while (i <= 5);
}

Output:
www.dotnetustad.com
www.dotnetustad.com
www.dotnetustad.com
www.dotnetustad.com
www.dotnetustad.com

In this example, the do-while loop starts with i initialized to 1. The loop body is executed first, and then the condition i <= 5 is checked. As long as the condition is true, the loop body is executed again. The loop continues until the condition becomes false.

Now we check 'do-while' with every false condition but it’s executed at least one time:


void dowhileloopDemo2()
{
   int i = 10;
   do
   {
     Console.WriteLine("www.dotnetustad.com");
     i++;
   }
   while (i <= 5); //condition is false even for the first time but it's executed
}

Output:
www.dotnetustad.com