C# While Loop

Repeating code while a condition is true

🔁 What is a While Loop?

A while loop repeatedly executes code as long as a specified condition remains true. It checks the condition before each iteration, making it perfect for unknown repetition counts.


// Simple while loop
int count = 1;
while (count <= 3)
{
    Console.WriteLine($"Count: {count}");
    count++;
}
                                    

Output:

Count: 1

Count: 2

Count: 3

Loop Concepts

🔄

While Loop

Check condition, then execute

while (x < 5)
{
    Console.WriteLine(x);
    x++;
}
🔃

Do-While Loop

Execute, then check condition

do
{
    Console.WriteLine(x);
    x++;
} while (x < 5);
🛑

Break Statement

Exit the loop early

while (true)
{
    if (x == 5) break;
    x++;
}
⏭️

Continue Statement

Skip to next iteration

while (x < 10)
{
    if (x == 5) continue;
    Console.WriteLine(x);
}

🔹 Basic While Loop

A while loop in Python repeatedly executes a block of code as long as a given condition remains True. It's ideal for scenarios where the number of iterations isn't known beforehand, like reading data until a sentinel value appears or validating user input. For example, a loop might increment a counter from 3 to 5 or count down from 5 to 1 before printing "Blast off!". It's crucial to ensure the condition eventually becomes false to avoid infinite loops.

// Counting from 1 to 5
int i = 1;
while (i <= 5)
{
    Console.WriteLine($"Number: {i}");
    i++;
}

// Countdown example
int countdown = 5;
while (countdown > 0)
{
    Console.WriteLine(countdown);
    countdown--;
}
Console.WriteLine("Blast off!");

Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

5

4

3

2

1

Blast off!

🔹 The Do-While Loop

Python doesn't have a built-in do-while loop, but its behavior—executing the block once before checking the condition—can be emulated. This pattern guarantees at least one iteration, making it perfect for menu-driven systems or initializing processes before validation. You can replicate it using a while True loop with a break statement after the first execution and a conditional check. This approach ensures code runs initially, even if the terminating condition is immediately met.

// Do-while always runs at least once
int number = 10;
do
{
    Console.WriteLine($"Number is: {number}");
    number++;
} while (number < 10);

// Menu example
int choice;
do
{
    Console.WriteLine("Menu:");
    Console.WriteLine("1. Start");
    Console.WriteLine("2. Exit");
    choice = 2; // Simulating user input
    
    if (choice == 1)
    {
        Console.WriteLine("Starting...");
    }
} while (choice != 2);
Console.WriteLine("Goodbye!");

Output:

Number is: 10

Menu:

1. Start

2. Exit

Goodbye!

🔹 Break Statement

The break statement provides an immediate exit from a loop, overriding its normal conditional control. It is commonly used to terminate a loop when a specific target is found (like locating a value in a list) or to stop an intentional infinite loop based on user input or an external event. For instance, you can loop through numbers 1 to 10 but break when reaching 5. This allows for efficient searching and responsive program flow without completing all iterations.

// Exit loop when condition is met
int num = 1;
while (num <= 10)
{
    Console.WriteLine(num);
    if (num == 5)
    {
        Console.WriteLine("Breaking at 5");
        break;
    }
    num++;
}

// Search example
int[] numbers = { 10, 20, 30, 40, 50 };
int searchFor = 30;
int index = 0;

while (index < numbers.Length)
{
    if (numbers[index] == searchFor)
    {
        Console.WriteLine($"Found {searchFor} at position {index}");
        break;
    }
    index++;
}

Output:

1

2

3

4

5

Breaking at 5

Found 30 at position 2

🔹 Continue Statement

The continue statement skips the remaining code in the current loop iteration and proceeds directly to the next cycle. It's useful for filtering out specific values without exiting the loop entirely. For example, you can process a list of numbers but use continue to skip even numbers, printing only odds. Or, you can skip processing for a particular invalid input. This helps in writing cleaner loops that handle exceptions or special cases gracefully within the iteration logic.

// Skip even numbers
int n = 0;
while (n < 10)
{
    n++;
    if (n % 2 == 0)
    {
        continue; // Skip even numbers
    }
    Console.WriteLine($"Odd number: {n}");
}

// Skip specific value
int counter = 0;
while (counter < 5)
{
    counter++;
    if (counter == 3)
    {
        Console.WriteLine("Skipping 3");
        continue;
    }
    Console.WriteLine($"Processing: {counter}");
}

Output:

Odd number: 1

Odd number: 3

Odd number: 5

Odd number: 7

Odd number: 9

Processing: 1

Processing: 2

Skipping 3

Processing: 4

Processing: 5

🔹 Nested While Loops

Nested while loops involve placing one while loop inside another, creating a multi-dimensional iteration structure. They are essential for working with grids, tables, or generating patterns like multiplication tables (e.g., a 3x3 grid) or star triangles. The inner loop completes all its iterations for each single iteration of the outer loop. This pattern is powerful for complex data processing, game boards, or any scenario requiring row-and-column logic, but careful management of loop variables is needed to avoid complexity.

// Multiplication table
int row = 1;
while (row <= 3)
{
    int col = 1;
    while (col <= 3)
    {
        Console.Write($"{row * col}\t");
        col++;
    }
    Console.WriteLine(); // New line after each row
    row++;
}

// Pattern printing
int i = 1;
while (i <= 3)
{
    int j = 1;
    while (j <= i)
    {
        Console.Write("* ");
        j++;
    }
    Console.WriteLine();
    i++;
}

Output:

1 2 3

2 4 6

3 6 9

*

* *

* * *

🔹 Practical Examples

While loops are fundamental for real-world programming tasks where repetition is conditional. Key applications include input validation (re-prompting a user until correct data is entered), accumulating a sum until a threshold is met, implementing password attempts with limited tries, or running a main game loop. Their flexibility makes them suitable for event-driven programming, processing streams of data, and controlling program states where the exact number of required repetitions cannot be predetermined before runtime.

// Sum numbers until zero
int sum = 0;
int input = 5; // Simulating user inputs
int[] inputs = { 5, 10, 15, 0 };
int idx = 0;

while (input != 0)
{
    sum += input;
    Console.WriteLine($"Current sum: {sum}");
    input = inputs[idx++]; // Get next input
}
Console.WriteLine($"Final sum: {sum}");

// Password validation (max 3 attempts)
string correctPassword = "secret";
string userPassword = "wrong";
int attempts = 0;
int maxAttempts = 3;

while (userPassword != correctPassword && attempts < maxAttempts)
{
    attempts++;
    Console.WriteLine($"Attempt {attempts}: Incorrect password");
    if (attempts == 2) userPassword = "secret"; // Correct on 3rd try
}

if (userPassword == correctPassword)
{
    Console.WriteLine("Access granted!");
}
else
{
    Console.WriteLine("Account locked");
}

Output:

Current sum: 5

Current sum: 15

Current sum: 30

Final sum: 30

Attempt 1: Incorrect password

Attempt 2: Incorrect password

Access granted!

🧠 Test Your Knowledge

What is the main difference between while and do-while loops?