C# while loop


The while loop in C# is a control structure that repeatedly executes a block of code as long as a specified condition is true. It checks the condition before executing the loop body, meaning if the condition is false from the beginning, the loop will not execute at all.

Syntax of while Loop:

while (condition) { // Code to be executed as long as the condition is true }
  • Condition: A boolean expression that is evaluated before each iteration. If true, the loop runs; if false, the loop terminates.
  • Loop Body: The block of code to be executed repeatedly while the condition remains true.

Example of a Basic while Loop:

int i = 1; while (i <= 5) { Console.WriteLine("Iteration: " + i); i++; // Increment i to eventually break the loop }

Explanation:

  • Initialization: int i = 1 sets up the loop control variable i with an initial value of 1.
  • Condition: The condition i <= 5 checks if i is less than or equal to 5. If true, the loop runs; otherwise, it stops.
  • Increment: Inside the loop, i++ increments the value of i by 1 after each iteration.
  • Loop Body: The statement Console.WriteLine("Iteration: " + i) prints the current value of i.

Output:

Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4 Iteration: 5

How the while Loop Works:

  1. Initialization: The loop begins by evaluating the condition i <= 5.
  2. Execution: If the condition is true, the loop body is executed.
  3. Increment/Update: The variable i is incremented by 1 in the loop body.
  4. Re-evaluation: The condition is checked again after each iteration.
  5. Termination: The loop ends when the condition becomes false (i.e., when i becomes 6).

Example with User Input:

You can use a while loop to continuously ask the user for input until they provide a specific value.

string input = ""; while (input != "exit") { Console.WriteLine("Type 'exit' to stop."); input = Console.ReadLine(); }

Explanation:

  • Initialization: The variable input is initialized with an empty string "".
  • Condition: The loop continues as long as input is not equal to "exit".
  • Loop Body: The loop prompts the user to type "exit" to stop and reads their input using Console.ReadLine().

Output:

Type 'exit' to stop. hello Type 'exit' to stop. world Type 'exit' to stop. exit

The loop will keep asking for input until the user types "exit".


Infinite Loop Example:

If the condition in the while loop always remains true, the loop will never terminate. This is known as an infinite loop.

while (true) { Console.WriteLine("This loop runs forever!"); }

In this case, the condition is always true, so the loop will continue indefinitely unless manually interrupted (e.g., by pressing Ctrl + C to stop the program).

Avoiding Infinite Loops:

It’s important to ensure that the condition in the while loop eventually becomes false or has a terminating condition, as demonstrated in the earlier examples.


Using break to Exit a while Loop:

You can use the break statement to exit a while loop early, based on certain conditions.

int i = 1; while (i <= 10) { if (i == 5) { break; // Exit the loop when i equals 5 } Console.WriteLine(i); i++; }

Explanation:

  • The loop will run from i = 1 to i = 10, but when i == 5, the break statement will cause the loop to terminate early.

Output:

1 2 3 4

The loop terminates when i == 5, so it prints only the first four numbers.


Using continue to Skip an Iteration:

The continue statement can be used to skip the current iteration and move to the next one.

int i = 0; while (i < 5) { i++; if (i == 3) { continue; // Skip the iteration when i equals 3 } Console.WriteLine(i); }

Explanation:

  • The loop increments i each time it iterates.
  • When i == 3, the continue statement skips that iteration, so the number 3 is not printed.

Output:

1 2 4 5

When to Use a while Loop:

  • Unknown Number of Iterations: Use a while loop when you don’t know beforehand how many times the loop will need to run. For example, when waiting for user input or processing data until a certain condition is met.

    Example: Reading user input until a valid value is entered or a file has been completely read.


Summary of while Loop in C#:

  • The while loop executes a block of code as long as the condition is true.
  • The loop will not execute at all if the condition is false from the start.
  • It’s ideal for cases where you don’t know how many iterations will be required in advance.
  • You can use break to exit the loop early or continue to skip an iteration.