A while loop is an entry-control loop that evaluates the condition before executing the block of the loop. If the condition is true then the body of the loop is executed else the loop will be skipped. The loop continues until the condition stated found to be false.
while loop Flowchart:
The syntax for while loop
in C#:
1 2 3 4 | while(condition) { //block of code to be executed } |
You should use a while loop, where the exact number of iterations is not known but the loop termination condition, is known.
Example of C# While Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; namespace Loops { class WhileProgram { static void Main(string[] args) { int i = 1; //while loop execution while (i <= 10) { Console.WriteLine("value of i: {0}", i); i++; } } } } |
Output:
1 2 3 4 5 6 7 8 9 10 | value of i: 1 value of i: 2 value of i: 3 value of i: 4 value of i: 5 value of i: 6 value of i: 7 value of i: 8 value of i: 9 value of i: 10 |