C# do-while loop

In C# do-while loop is similar to while loop which we read in last chapter. the only difference is, in do-while loop is, code is executed at least once because condition is checked after loop body.

Syntax

    do{  
    //code to be executed  
    }while(condition);  

So, as you see in the above syntax. first code is executed which is inside braces, and then condition is checked, so code is executed at-least one time before condition is checked.

Also, notice the semi-colon at the end, which is required.

Example:

    using System;  
    public class DoWhileLoopExample  
        {  
          public static void Main(string[] args)  
          {  
              int i = 1;  
                
              do{  
                  Console.WriteLine(i);  
                  i++;  
              } while (i <= 10) ;  
        
         }  
       }  

Output:

1
2
3
4
5
6
7
8
9
10

Nested Do while loop

When we use do-while inside another do-while it is known as nested do-while, take a look at the below example

using System;
					
public class NestedDoWhileProgram
{
	public static void Main()
	{		
         int i=1; 
		//first do while
          do{  
              int j = 1;  
                //second do while
              do{  
                  Console.WriteLine(i+" "+j);  
                  j++;  
              } while (j <= 3) ;
			  Console.WriteLine("End of loop "+i +" for outer do while");
              i++;  
          } while (i <= 3);

	}
}

Output

1 1
1 2
1 3
End of loop 1 for outer do while
2 1
2 2
2 3
End of loop 2 for outer do while
3 1
3 2
3 3
End of loop 3 for outer do while

Break do-while loop

Using break keyword, we can exit from the loop, before completing actual all the loop conditions, for example

    using System;  
    public class DoWhileLoopExample  
        {  
          public static void Main(string[] args)  
          {  
              int i = 1;  
                
              do{  
                  Console.WriteLine(i);  
                  
				  //check if value of i is 5
				  if(i==5)
				  {
					  //if value of i is 5, exit from loop and it will not print remaining values
					  break;
				  }
				  i++;  
              } while (i <= 10) ;  
        
         }  
       }  

In the above do-while loop, we have added another condition, if i=5, break the do-while loop, so it will not print values after 5 and exit from the loop.

Output:

1
2
3
4
5

Share Tweet