0
0
C Sharp (C#)programming~5 mins

While loop execution model in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of actions as long as a condition is true. It saves time by avoiding writing the same code again and again.

When you want to keep asking a user for input until they give a valid answer.
When you want to keep counting or processing items until a certain limit is reached.
When you want to repeat an action until something changes, like waiting for a file to appear.
When you don't know in advance how many times you need to repeat something.
Syntax
C Sharp (C#)
while (condition)
{
    // code to repeat
}

The condition is checked before each repetition.

If the condition is false at the start, the code inside the loop does not run at all.

Examples
This prints numbers 0, 1, and 2. The loop stops when count reaches 3.
C Sharp (C#)
int count = 0;
while (count < 3)
{
    Console.WriteLine(count);
    count++;
}
This runs the loop once because keepGoing becomes false inside the loop.
C Sharp (C#)
bool keepGoing = true;
while (keepGoing)
{
    Console.WriteLine("Running...");
    keepGoing = false;
}
Sample Program

This program prints numbers from 1 to 5 using a while loop. It shows how the loop runs repeatedly while the condition is true.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int number = 1;
        while (number <= 5)
        {
            Console.WriteLine($"Number is {number}");
            number++;
        }
    }
}
OutputSuccess
Important Notes

Make sure the condition will eventually become false, or the loop will run forever (infinite loop).

You can use break; inside the loop to stop it early if needed.

Summary

A while loop repeats code as long as a condition is true.

The condition is checked before each repetition.

Use while loops when you don't know how many times you need to repeat something.