While Loop

A while loop in C# is a control flow statement that allows you to repeat a code block if a specified condition remains true. This can be particularly useful when you don’t know in advance how many times you need to execute a block of code, but you want to keep looping until a certain condition is met.

Structure of a while Loop

The basic structure of a while loop includes:
  • The while keyword followed by a condition in parentheses.
  • A block of code enclosed in curly braces {} that will be executed repeatedly as long as the condition evaluates to true.

Syntax for a while loop in C#

while (condition)
{
  // Code to be executed
}

Example

using System;

class Program
{
  static void Main()
  {
      int counter = 12;
      while (counter > 0)
      {
          Console.WriteLine(counter);
          counter--;
      }
      Console.WriteLine("Blast off!");
  }
}

Explanation of the Example

  1. Initialization: We start by initializing an integer variable counter with the value 12.
  2. Condition: The while loop checks if the value of counter is greater than 0. Since the initial value is 12, the condition is true, and the loop body is executed.
  3. Loop Body: Inside the loop body:
    • The current value of counter is printed to the console.
    •  The counter is then decremented by 1 using the — operator.
  4. Re-Evaluation: After executing the loop body, the condition is re-evaluated. If counter is still greater than 0, the loop continues; otherwise, it exits the loop.
  5. Termination: Once the loop condition is false (i.e., counter is no longer greater than 0), the loop terminates, and the program prints “Blast off!” to the console.

Use Cases for while Loops

  1. Reading User Input: You can use a while loop to repeatedly prompt the user for input until they enter a valid response.
  2. Monitoring Processes: Continuously check the status of a process or a condition (e.g., waiting for a file to be available).
  3. Game Loops: In simple games, a while loop can keep the game running until a certain condition (like game over) is met.

Nested while Loops

while loops can also be nested within each other to handle more complex scenarios. For instance, consider a program that prints a multiplication table:
using System;

class Program
{
  static void Main()
  {
      int i = 1;
      while (i <= 10)
      {
          int j = 1;
          while (j <= 10)
          {
              Console.Write("{0} x {1} = {2}\t", i, j, i * j);
              j++;
          }
          Console.WriteLine();
          i++;
      }
  }
}

Explanation of the Nested Example

  1. Outer Loop: The outer while loop runs from i = 1 to i = 10.
  2. Inner Loop: For each iteration of the outer loop, the inner while loop runs from j = 1 to j = 10.
  3. Multiplication: The inner loop calculates the product of i and j and prints it in a formatted string.
  4. Output Formatting: After the inner loop completes, a new line is printed to start the next row of the multiplication table.
This nested while loop example demonstrates how you can use multiple while loops together to handle more complex logic and output formatting.

Best Practices for While Loop

  1. Avoid Infinite Loops: Ensure that the loop condition will eventually become false to avoid infinite loops that can crash your program.
  2. Use Break Statements: In some scenarios, you can use a break statement to exit the loop prematurely if a certain condition is met.
  3. Keep It Simple: Keep the loop body concise and focused to improve readability and maintainability.
Post a comment

Leave a Comment

Scroll to Top