C# provides the while loop to repeatedly execute a block of code as long as the specified condition returns false. The while loop starts with the while keyword, and it must include a boolean conditional expression inside brackets that returns either true or false. It executes the code block until the specified conditional expression returns false. The condition is given in the beginning of the loop and all statements are executed till the given boolean condition satisfies when the condition becomes false, the control will be out from the while loop else It executes the code block until the specified conditional expression returns false.

Syntax of While Loop

while (boolean condition) {
// code of block to be executed
}

Example 1: while Loop

using System;
public class Program
{
public static void Main()
{
int i = 1; // initialization
int m = 2;
while (i < 10) // condition
{
Console.WriteLine(m + " Multiply By " + i + " is - " + m*i);
i++; // increment
}
}
}

The output will be:

2 Multiply By 1 is - 2
2 Multiply By 2 is - 4
2 Multiply By 3 is - 6
2 Multiply By 4 is - 8
2 Multiply By 5 is - 10
2 Multiply By 6 is - 12
2 Multiply By 7 is - 14
2 Multiply By 8 is - 16
2 Multiply By 9 is - 18

Example 2: while Loop

using System;
public class Program
{
public static void Main()
{
int i = 10; // initialization
// Exit when i becomes less than 1
while (i >= 1) // condition
{
Console.WriteLine("The Value of i is " + i);
i--; // increment
}
}
}

The output will be:

The Value of i is 10
The Value of i is 9
The Value of i is 8
The Value of i is 7
The Value of i is 6
The Value of i is 5
The Value of i is 4
The Value of i is 3
The Value of i is 2
The Value of i is 1