C# - While Loop



C# while loop is a basic control flow statement that allows repeated execution of a block of code as long as a specified condition evaluates to true. This loop construct is useful when the number of iterations is not predetermined.

Syntax of while Loop

Following is the syntax of the C# while loop −

while(condition) {
   statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

Flow Diagram of while Loop

while loop in C#

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body is skipped and the first statement after the while loop is executed.

Parts of a while Loop

A while loop has three main parts:

  • Initialization: In a counter-controlled loop, where the number of iterations is known, this step defines the counter variable before the loop starts.
  • Condition: The loop runs as long as this condition is true.
  • Update (Increment/Decrement): The counter variable inside the condition should change in each iteration to prevent an infinite loop.

Syntax

// Initialization
int i = 0;

// while loop with condition
while (i < 5) {
    Console.WriteLine(i);
    
    // Update (Increment)
    i++;
}

Example of a while Loop

In the following example, we display the numbers from 10 to 20 using the while loop −

using System;
namespace Loops {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;

         /* while loop execution */
         while (a <= 20) {
            Console.WriteLine("value of a: {0}", a);
            a++;
         }
         Console.ReadLine();
      }
   }
} 

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

More Examples of while Loop

1. Finding Sum of First n Natural Numbers

Let's see another example of the while loop. Here, we calculate the sum of the first n natural numbers −

using System;
class Example {
   static void Main(string[] args) {
      int n = 5, sum = 0, i = 1;
   
      while (i <= n) {
         sum += i; 
         i++;
      }  
      Console.WriteLine("Sum of first " + n + " numbers is: " + sum);
   }
}

Following is the output of the above code −

Sum of first 5 numbers is: 15

2. Reversing a Number

In this example, we use a while loop to reverse a given number:

using System;
class Example {
   static void Main(string[] args) {
      int num = 12345, reverse = 0;
   
      while (num != 0) {
         int digit = num % 10; // Extract last digit
         reverse = reverse * 10 + digit;
         num /= 10; // Remove last digit
      }  
      Console.WriteLine("Reversed Number: " + reverse);
   }
}

Following is the output of the above code −

Reversed Number: 54321

3. Counting Digits in a Number

In this example, we use a while loop to count the number of digits in an integer:

using System;
class Example {
   static void Main(string[] args) {
      int num = 987654, count = 0;
   
      while (num != 0) {
         num /= 10; // Remove last digit
         count++;
      }  
      Console.WriteLine("Total Digits: " + count);
   }
}

Following is the output of the above code −

Total Digits: 6

Use Cases of while Loop

Here are some common use cases:

1. Reading User Input Until a Condition is Met

The while loop can be used for continues accepting input from the user until they enter a specific value.

using System;
class Example {
    static void Main() {
        string input;
        while (true) {
            Console.Write("Enter a word (type 'exit' to stop): ");
            input = Console.ReadLine();
            if (input == "exit")
                break;
            Console.WriteLine("You entered: " + input);
        }
    }
}

2. Looping Until a Valid Input is Entered

The while loop ensures that users provide a correct input before proceeding.

using System;
class Example {
    static void Main() {
        int number;
        Console.Write("Enter a positive number: ");
        while (!int.TryParse(Console.ReadLine(), out number) || number <= 0) {
            Console.Write("Invalid input! Please enter a positive number: ");
        }
        Console.WriteLine("You entered: " + number);
    }
}

3. Processing Files Until the End is Reached

The while loop is useful for reading files line by line until no more data is available.

using System;
using System.IO;
class Example {
    static void Main() {
        string filePath = "sample.txt";
        if (File.Exists(filePath)) {
            using (StreamReader reader = new StreamReader(filePath)) {
                string line;
                while ((line = reader.ReadLine()) != null) {
                    Console.WriteLine(line);
                }
            }
        }
    }
}

4. Generating Random Numbers Until a Condition is Met

This while loop is useful in games or simulations where a condition is checked dynamically.

using System;
class Example {
    static void Main() {
        Random rand = new Random();
        int number;
        do {
            number = rand.Next(1, 10);
            Console.WriteLine("Generated: " + number);
        } while (number != 7);
        Console.WriteLine("Stopped at 7!");
    }
}

5. Running a Background Task Until a Stop Condition

The while loop can be used for continuously checking system status or waiting for a flag to change.

using System;
using System.Threading;
class Example {
    static void Main() {
        bool isRunning = true;
        int counter = 0;
        while (isRunning) {
            Console.WriteLine("Running... " + counter);
            Thread.Sleep(1000); // Simulates a delay
            counter++;
            if (counter == 5) isRunning = false;
        }
        Console.WriteLine("Process stopped.");
    }
}
Advertisements