C# while loop Statements

In C#, the while loop statement allows you to execute a block of code repeatedly while a certain condition is true. The while loop is a pretest loop, which means that the condition is tested before the loop body is executed.

Syntax

Here is the basic syntax of the while loop statement:

1while (condition) 2{ 3 // Code to be executed 4}

The condition is an expression that is evaluated before each iteration of the loop. If the condition is true, the loop body will be executed. If the condition is false, the loop will be terminated and control will be passed to the next statement after the loop body.

Examples

Example 1: Printing numbers from 1 to 5

The following code demonstrates how to use a while loop to print the numbers from 1 to 5:

1int i = 1; 2while (i <= 5) 3{ 4 Console.WriteLine(i); 5 i++; 6}

The output of this code will be:

11 22 33 44 55

Example 2: Calculating the factorial of a number

The following code demonstrates how to use a while loop to calculate the factorial of a number:

1int n = 5; 2int factorial = 1; 3while (n > 1) 4{ 5 factorial *= n; 6 n--; 7} 8Console.WriteLine("Factorial of 5 is " + factorial);

The output of this code will be: Factorial of 5 is 120

Example 3: Infinite loop

If the condition in the while loop is always true, the loop will never terminate and you will end up with an infinite loop. Here is an example of an infinite loop:

1while (true) 2{ 3 Console.WriteLine("This is an infinite loop"); 4}

To stop an infinite loop, you can use the break statement.