C Sharp Do While Loop

C# Do-While Loop

To iterate a specified code for multiple times, the C# Do-While loop is used. It is recommended to use the Do-While loop when the number of iterations is not fixed and the loop needs to be executed at least once. The loop is executed at least once because, in C# do-while loop, the condition is checked after the loop body.

Syntax:

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

Example:

using System;  
public class Example  
    {  
      public static void Main(string[] args)  
      {  
          char x = 'a';  
 
          do{  
              Console.WriteLine(x);  
              x++;  
          } while (x <= 'p') ; 
     }  
   }

Output:

Explanation:

In the above example, we are using a simple program to display the use of the Do-While loop in C#.

C# Nested do-while Loop:

When a Do-While loop is used inside another Do-While loop, then it is called the nested Do-While loop in C#. The outer loop of a nested Do-While loop is executed only one time when the inner loop of the nested Do-While loop is completely executed.

Example:

using System;  
public class Example  
    {  
      public static void Main(string[] args)  
      {  
          char x = 'a';  
 
          do{  
              int y = 1;  
              do{  
                  Console.WriteLine(x +" "+ y);  
                  y++;  
              } while (y <= 4) ;  
              x++;  
          } while (x <= 'd') ;  
 
     }  
   }

Output:

Explanation:

In the above example, we are using a simple program to display the use of the Nested Do-While loop in C#.

C# Infinitive do-while Loop:

To execute a Do-While loop for the infinite times, true is passed as the test condition in the Do-While loop, and such a loop is called the Infinitive Do-While loop in C#.

Syntax:

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

Example:

using System;  
public class Example  
    {  
      public static void Main(string[] args)  
      {      
          do{  
               Console.WriteLine("Stop Me if you can!!");   
          } while (true) ;  
 
     }  
   }

Output:

Explanation:

In the above example, we are using a simple program to display the use of the Infinitive Do-While loop in C#.

Please Share