C# While Loop
To iterate a specified code for multiple times, the C# While loop is used. It is recommended to use the While loop when the number of iterations is not fixed. The syntax and behavior of C# While loop are the same as that in C or C++.
Syntax:
while(condition) { //code to be executed }
Example:
using System; public class Example { public static void Main(string[] args) { char x='a'; while(x<='p') { Console.WriteLine(x); x++; } } } |
Output:
Explanation:
In the above example, we are using a simple program to display the use of the While loop in C#.
C# Nested While Loop:
When a While loop is used inside another While loop, then it is called nested While loop in C#. The outer loop of a nested While loop is executed only one time when the inner loop of the nested While loop is completely executed, i.e, if the outer loop is executed 3 times and the inner loop is executed 5 times, then the inner loop will be executed 5 times for each outer loop i.e. total 15 times.
Example:
using System; public class Example { public static void Main(string[] args) { char x='a'; while(x<='d') { int y = 1; while (y <= 4) { Console.WriteLine(x +" "+ y); y++; } x++; } } } |
Output:
Explanation:
In the above example, we are using a simple program to display the use of the Nested While loop in C#.
C# Infinitive While Loop:
To execute a While loop for the infinite times, true is passed as the test condition in While loop, and such a loop is called Infinitive While loop in C#.
Example:
using System; public class Example { public static void Main(string[] args) { while(true) { Console.WriteLine("Stop Me if you can!!"); } } } |
Output:
Explanation:
In the above example, we are using a simple program to display the use of the Infinitive While loop in C#.