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

C# While loop – Interview Questions

Q 1: What is a while loop?

Ans: A while loop executes code as long as a condition is true.

Q 2: When is while loop preferred?

Ans: When the number of iterations is not known in advance

Q 3: Does while loop check condition first?

Ans: Yes, it checks the condition before executing the loop body.

Q 4: Can a while loop run zero times?

Ans: Yes, if the condition is false initially.

Q 5: Can while loop be nested?

Ans: Yes.

C# While loop – Objective Questions (MCQs)

Q1. When is the condition checked in a while loop?






Q2. What will happen if the condition in a while loop is initially false?






Q3. Which of the following is the correct syntax for a while loop?






Q4. What is the correct syntax of a foreach loop?






Q5. Is it possible to create an infinite while loop in C#?






Related C# While loop Topics