467
The while loop in C# is a control flow statement that allows code to be executed repeatedly as long as a specified condition remains true.
It is useful when the number of iterations is not known in advance.
This tutorial covers:
- Syntax of the while Loop
- How the while Loop Works
- Example Usage of while Loop
- Using break and continue in a while Loop
- Handling Infinite Loops
- The while Loop with User Input
- Using a while Loop with Arrays and Lists
- Best Practices for Using while Loops
1. Syntax of the while Loop
The while loop repeatedly executes a block of code as long as the condition evaluates to true.
Syntax
while (condition)
{
// Code to be executed
}
- The condition is checked before each iteration.
- If the condition is false initially, the loop does not run.
2. How the while Loop Works
- The condition is evaluated.
- If true, the loop body executes.
- The condition is checked again after execution.
- The process repeats until the condition becomes false.
Example: Basic while Loop
int count = 1;
while (count <= 5)
{
Console.WriteLine("Iteration " + count);
count++; // Increment count
}
Output:
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
- count starts at 1 and increments by 1 each time.
- The loop stops when count > 5.
3. Example Usage of while Loop
Using a while Loop for a Countdown
int number = 5;
while (number > 0)
{
Console.WriteLine("Countdown: " + number);
number--; // Decrease number by 1
}
Console.WriteLine("Liftoff!");
Output:
Countdown: 5 Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 Liftoff!
- The loop decrements number until it reaches 0.
4. Using break and continue in a while Loop
Using break to Exit the Loop
The break statement immediately exits the loop, regardless of the condition.
int num = 1;
while (num <= 10)
{
if (num == 5)
{
Console.WriteLine("Stopping loop at " + num);
break; // Exit the loop
}
Console.WriteLine(num);
num++;
}
Output:
1 2 3 4 Stopping loop at 5
- The loop stops when num == 5.
Using continue to Skip an Iteration
The continue statement skips the current iteration and moves to the next.
int num = 0;
while (num < 5)
{
num++;
if (num == 3)
{
Console.WriteLine("Skipping " + num);
continue; // Skips iteration when num == 3
}
Console.WriteLine(num);
}
Output:
1 2 Skipping 3 4 5
- The loop skips num = 3 but continues running.
5. Handling Infinite Loops
A while loop can become infinite if the condition never becomes false.
Example of an Infinite Loop
int i = 1;
while (i > 0) // Always true
{
Console.WriteLine("This is an infinite loop");
}
- This loop never stops.
Fixing an Infinite Loop
Always ensure the loop updates the condition.
int i = 1;
while (i <= 5)
{
Console.WriteLine("Iteration " + i);
i++; // Ensure condition will become false
}
6. The while Loop with User Input
A while loop is often used to repeatedly ask for user input.
Example: Asking for a Valid Number
int number;
Console.Write("Enter a number greater than 0: ");
while (!int.TryParse(Console.ReadLine(), out number) || number <= 0)
{
Console.Write("Invalid input. Enter a number greater than 0: ");
}
Console.WriteLine("You entered: " + number);
- TryParse() ensures only valid numbers are accepted.
- The loop repeats until valid input is given.
7. Using a while Loop with Arrays and Lists
Iterating Through an Array Using while
int[] numbers = { 10, 20, 30, 40, 50 };
int index = 0;
while (index < numbers.Length)
{
Console.WriteLine(numbers[index]);
index++; // Move to the next index
}
Output:
10 20 30 40 50
- The loop runs until the end of the array.
Iterating Through a List Using while
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int index = 0;
while (index < names.Count)
{
Console.WriteLine(names[index]);
index++;
}
}
}
Output:
Alice Bob Charlie
- names.Count provides the list size.
8. Best Practices for Using while Loops
Use a while Loop When the Number of Iterations is Unknown
while (userInput != "exit")
- Use while when the number of iterations is dynamic.
Ensure the Condition Will Eventually Become False
while (count > 0)
{
count--; // Prevents infinite loop
}
- Always modify the loop variable.
Use break to Exit the Loop If Needed
while (true)
{
string input = Console.ReadLine();
if (input == "exit")
{
break; // Exit the loop when "exit" is entered
}
}
- break is useful for user-controlled exits.
Use continue to Skip Unwanted Iterations
while (index < 10)
{
index++;
if (index % 2 == 0) continue; // Skip even numbers
Console.WriteLine(index);
}
- continue helps skip unnecessary operations.
Use TryParse() for Safe User Input
while (!int.TryParse(Console.ReadLine(), out int value))
{
Console.WriteLine("Invalid input. Try again.");
}
- This prevents crashes from invalid input.
Conclusion
- The while loop executes code repeatedly while a condition is true.
- Use while when the number of iterations is unknown.
- Use break to exit early and continue to skip an iteration.
- Ensure the loop condition eventually becomes false to avoid infinite loops.
- Use while loops for handling user input and processing lists/arrays.
