C# While Loop
Introduction
The while
loop is one of the fundamental loop structures in C#. It allows you to repeatedly execute a block of code as long as a specified condition evaluates to true
. This is particularly useful when you don't know beforehand how many times you need to execute a code block.
Unlike a for
loop which is often used when the number of iterations is known, a while
loop is ideal for situations where the loop should continue until a certain condition is no longer valid.
Basic Syntax
The syntax for a while
loop in C# is:
while (condition)
{
// Code to be executed
}
The flow of execution is:
- The condition is evaluated
- If the condition is
true
, the code block is executed - After execution, the condition is evaluated again
- Steps 2-3 repeat until the condition becomes
false
Simple While Loop Example
Let's start with a basic example that counts from 1 to 5:
using System;
class Program
{
static void Main()
{
int i = 1;
while (i <= 5)
{
Console.WriteLine($"Count: {i}");
i++;
}
Console.WriteLine("Loop finished!");
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished!
In this example:
- We initialize
i
with the value1
before entering the loop - The loop continues as long as
i
is less than or equal to5
- Inside the loop, we print the current value of
i
and then increment it - Once
i
becomes6
, the conditioni <= 5
becomesfalse
, and the loop terminates
Importance of Loop Control Variables
When using a while
loop, it's crucial to make sure that:
- The condition will eventually become
false
to avoid infinite loops - The condition variables are properly initialized before the loop
- The condition variables are updated within the loop
If you forget to update the condition variable, you'll create an infinite loop:
int i = 1;
while (i <= 5)
{
Console.WriteLine($"Count: {i}");
// Forgot to increment i! This will cause an infinite loop
}
Using While Loops with User Input
While loops are excellent for validating user input. Here's an example that asks the user to enter a positive number:
using System;
class Program
{
static void Main()
{
int number = -1;
while (number <= 0)
{
Console.Write("Please enter a positive number: ");
string input = Console.ReadLine();
if (int.TryParse(input, out number))
{
if (number <= 0)
{
Console.WriteLine("That's not a positive number. Try again.");
}
}
else
{
Console.WriteLine("Invalid input. Please enter a number.");
number = -1;
}
}
Console.WriteLine($"Thank you! You entered: {number}");
}
}
Example interaction:
Please enter a positive number: -5
That's not a positive number. Try again.
Please enter a positive number: zero
Invalid input. Please enter a number.
Please enter a positive number: 10
Thank you! You entered: 10
This example demonstrates how to use a while
loop to repeatedly prompt the user until valid input is received.
While vs. Do-While Loop
A variation of the while
loop is the do-while
loop. The key difference is that a do-while
loop executes the code block at least once before checking the condition:
// While loop - might not execute at all if condition is initially false
while (condition)
{
// Code to be executed
}
// Do-while loop - always executes at least once
do
{
// Code to be executed
} while (condition);
Nested While Loops
Like other loop structures, while
loops can be nested within each other:
using System;
class Program
{
static void Main()
{
int i = 1;
while (i <= 3)
{
int j = 1;
while (j <= 2)
{
Console.WriteLine($"i = {i}, j = {j}");
j++;
}
i++;
Console.WriteLine("--------");
}
}
}
Output:
i = 1, j = 1
i = 1, j = 2
--------
i = 2, j = 1
i = 2, j = 2
--------
i = 3, j = 1
i = 3, j = 2
--------
Practical Example: Simple Number Guessing Game
Now let's create a more practical example - a number guessing game:
using System;
class Program
{
static void Main()
{
Random random = new Random();
int secretNumber = random.Next(1, 101); // Random number between 1 and 100
int guess = 0;
int attempts = 0;
bool hasWon = false;
Console.WriteLine("Welcome to the Number Guessing Game!");
Console.WriteLine("I've selected a number between 1 and 100.");
while (!hasWon && attempts < 7)
{
Console.Write("Enter your guess: ");
string input = Console.ReadLine();
if (int.TryParse(input, out guess))
{
attempts++;
if (guess < secretNumber)
{
Console.WriteLine("Too low! Try again.");
}
else if (guess > secretNumber)
{
Console.WriteLine("Too high! Try again.");
}
else
{
hasWon = true;
Console.WriteLine($"Congratulations! You guessed the number {secretNumber} in {attempts} attempts!");
}
}
else
{
Console.WriteLine("Invalid input. Please enter a number.");
}
Console.WriteLine($"Attempts left: {7 - attempts}");
}
if (!hasWon)
{
Console.WriteLine($"Sorry, you've used all your attempts. The secret number was {secretNumber}.");
}
}
}
This example showcases a complete game that:
- Generates a random number
- Uses a while loop to give the player multiple attempts
- Provides feedback after each guess
- Tracks and limits the number of attempts
- Handles invalid input
Breaking Out of While Loops
Sometimes you need to exit a loop early based on a specific condition. You can use the break
statement for this:
using System;
class Program
{
static void Main()
{
int i = 1;
while (i <= 10)
{
Console.WriteLine($"Number: {i}");
// Exit the loop when i reaches 5
if (i == 5)
{
Console.WriteLine("Breaking out of the loop!");
break;
}
i++;
}
Console.WriteLine("Loop terminated");
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Breaking out of the loop!
Loop terminated
Skipping Iterations with Continue
You can also use the continue
statement to skip the current iteration and proceed with the next one:
using System;
class Program
{
static void Main()
{
int i = 0;
while (i < 10)
{
i++;
// Skip printing even numbers
if (i % 2 == 0)
{
continue;
}
Console.WriteLine($"Odd number: {i}");
}
}
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
Common Pitfalls
1. Infinite Loops
The most common error when working with while loops is creating an infinite loop by forgetting to update the condition variable:
// Infinite loop - i is never updated
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
// Missing i++ statement!
}
2. Off-by-One Errors
Be careful about the boundary conditions in your loops:
// Will run from 1 to 5 (inclusive)
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
// Will run from 1 to 4 (exclusive of 5)
int j = 1;
while (j < 5)
{
Console.WriteLine(j);
j++;
}
3. Condition Evaluation Timing
Remember that the condition is evaluated at the beginning of each iteration:
int x = 10;
while (x > 0)
{
Console.WriteLine(x);
x -= 2;
}
// Outputs: 10, 8, 6, 4, 2
Performance Considerations
While loops are efficient for situations where the number of iterations is unknown beforehand. However, if you know exactly how many iterations you need, a for
loop might be more appropriate and clearer to read.
Summary
The while
loop in C# is a powerful tool that allows you to:
- Execute code repeatedly as long as a specified condition is true
- Handle situations where the number of iterations isn't known beforehand
- Process user input until valid data is entered
- Create interactive programs like simple games
- Control loop execution with
break
andcontinue
statements
When using while loops, always ensure that:
- The loop condition will eventually become false
- The condition variables are properly initialized and updated
- You avoid common pitfalls like infinite loops
- You choose the right loop structure for your specific use case
Exercises
-
Write a program that calculates the sum of all integers from 1 to n, where n is entered by the user.
-
Create a program that prints the first 10 numbers in the Fibonacci sequence using a while loop.
-
Write a program that reverses a number entered by the user (e.g., input 123 should output 321).
-
Create a simple calculator program that keeps asking the user for operations until they enter 'q' to quit.
-
Implement a "high-low" guessing game where the computer has to guess a number that the user thinks of.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)