While Loop in C#

While loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true.

While loop always check the condition first before executing any code.

Syntax

while (condition)
{
    // Code to execute while the condition is true
}

Example. Print numbers from 0 to 10.

int i = 0;
while (i < 10)
{
    Console.WriteLine(i);
    i++;
}

Explanation

int i = 0;

This line initializes a variable i with the value 0. This variable will be used as a counter to control the loop.

while (i < 10)

Here, while is a keyword indicating the start of a while loop. The condition (i < 10) is checked before each iteration of the loop. If the condition is true, the loop body will be executed; otherwise, the loop will terminate. In this case, the loop will continue as long as the value of i is less than 10.

{
    Console.WriteLine(i);
    i++;
}

This is the body of the while loop. Inside the curly braces {}, you have the code that will be executed repeatedly as long as the condition is true. In this case, it prints the current value of i using Console.WriteLine(i); and then increments the value of I by 1 using i++.

So, this loop will print the numbers from 0 to 9 (inclusive) because it starts with i = 0 and increments i by 1 in each iteration until i becomes 10, at which point the loop terminates.

Result

0

1

2

3

4

5

6

7

8

9


Similar Articles