C# While loop

A while loop in C# is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to true. The loop checks the condition before each iteration, and if the condition remains true, the loop continues executing the code. If the condition is false at any point, the loop exits and the program moves to the next statement after the loop.

In the while loop, first of all, the Boolean expression is calculated, and if it is true, the sequence of operations in the body of the loop is executed.

Then again, the input condition is checked, and if it is true again the body of the loop is executed. All this is repeated again and again until, at some point, the conditional expression returns a value of false

Syntax:


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

Explanation:

condition: A boolean expression that is checked before each iteration. If it is true, the loop continues; if false, the loop terminates.

Example: Print the value from 1 to 5


using System;

class ProgramExample
{
    static void Main()
    {
        int number = 1; // Initialize the number variable
        // While loop that runs until number is less than or equal to 5
        while (number <= 5)
        {
            Console.WriteLine(number); // Prints the current value of number
            number++; // Increment count after each iteration
        }
    }
}

Output:

1
2
3
4
5