C# While Loop

The while loop in C# repeatedly executes a block of code as long as a specified condition evaluates to true. It is useful when the number of iterations is not known in advance and depends on a condition that is evaluated during each iteration.

Key Topics

1. Syntax of While Loop

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

The condition is evaluated before each iteration. If it is true, the code block executes. If it is false, the loop terminates.

2. Basic While Loop Example

Example: Counting from 1 to 5

int i = 1;
while (i <= 5)
{
    Console.WriteLine(i);
    i++;
}

Output:

1
2
3
4
5

Code Explanation: The variable i starts at 1. The loop continues as long as i <= 5. After each iteration, i is incremented by 1.

3. While Loop with a Condition

Example: Printing Even Numbers

int number = 2;
while (number <= 10)
{
    Console.WriteLine(number);
    number += 2;
}

Output:

2
4
6
8
10

Code Explanation: Starting from 2, the loop prints even numbers by incrementing number by 2 each time, until it exceeds 10.

4. While Loop with User Input

Example: Prompting Until Exit

string input = "";
while (input != "exit")
{
    Console.WriteLine("Type something (type 'exit' to quit):");
    input = Console.ReadLine();
}

Code Explanation: The loop continues to prompt the user until they type "exit". The condition checks if input is not equal to "exit".

5. Infinite While Loop (with Break)

Example: Controlled Infinite Loop

int counter = 0;
while (true)
{
    counter++;
    Console.WriteLine("Counter: " + counter);
    if (counter >= 5)
    {
        break;  // Exit the loop when counter reaches 5
    }
}

Code Explanation: The loop is intentionally infinite with while (true). The break statement exits the loop when counter reaches 5.

6. Best Practices for While Loops

  • Ensure that the loop condition will eventually become false to avoid infinite loops.
  • Use break statements cautiously to control loop execution.
  • Initialize loop variables before the loop starts.
  • Be careful with loop conditions involving user input or external factors.

Key Takeaways

  • The while loop repeats code as long as a condition is true.
  • It is suitable when the number of iterations is not known beforehand.
  • Properly managing loop conditions and variables prevents infinite loops.
  • Using break statements can help exit loops based on certain conditions.
  • Always consider loop termination conditions when dealing with user input.