C# While Loop

while loop iterates a part of the code until the given condition fails. This is an entry controlled loop. While loop is recommended to use if the condition depends on the user or not known In advance. Let's see a simple example of while loop.


Syntax
while(<condition>)
{
//statements
}
C# While loop example:
using System;
public class WhileLoopExample1
{
            public static void Main (string[] args)
            {
            int i=1;
                        while(i<10)
                        {
                                    Console.WriteLine(i);
                                    i++;
                        }
}
}
Output
1
2
3
4
5
6
7
8
9
C# nested while loop: Nested while loop is almost similar to nested for loop. We can use while loop inside a while loop. The inner will execute n number of time for each iteration of outer loop.
C#  Nested While loop Example:
using System;  
            public class WhileExample  
                {  
                  public static void Main(string[] args)  
                  {  
                      int i=1;    
                      while(i<=3)   
                      {  
                          int j = 1;  
                          while (j<=3)  
                                                  {  
                              Console.WriteLine(i+""+j);  
                              j++;  
                          }  
                          i++;  
                      }    
                 }  
               }
Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
C# infinite while loop example: If we put a condition in while loop that never fails then the loop becomes an infinite loop .
using System;
public class InfiniteWhileLoopExample{
public static void main (String[] args)
{
While(true)
{
            //some statements 
}
}
}