The while
loop in C# is a control structure that allows code to repeat as long as a specified condition remains true. It is ideal when you don’t know the exact number of iterations beforehand, but you have a condition that controls the loop.
In this tutorial, we’ll cover:
1. Basic Structure of a while
Loop
The while
loop checks a condition before each iteration. If the condition is true
, it runs the loop body; otherwise, it exits the loop.
Syntax:
while (condition)
{
// Code to execute as long as the condition is true
}
Example:
using System;
public class WhileLoopExample
{
public static void Main()
{
int counter = 1;
while (counter <= 5)
{
Console.WriteLine("Iteration: " + counter);
counter++;
}
}
}
In this example:
- The
counter
variable is initialized to 1. - The loop checks if
counter
is less than or equal to 5. Iftrue
, it prints the iteration and incrementscounter
. - The loop stops once
counter
becomes 6.
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
2. while
Loop with User Input
The while
loop is commonly used to process user input until a certain condition is met.
Example:
using System;
public class WhileUserInputExample
{
public static void Main()
{
string input = "";
while (input != "exit")
{
Console.Write("Enter a command (type 'exit' to quit): ");
input = Console.ReadLine();
Console.WriteLine("You entered: " + input);
}
}
}
In this example:
- The loop will continue prompting the user to enter a command.
- When the user types “exit,” the condition
input != "exit"
becomesfalse
, and the loop stops.
3. The do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the loop body will execute at least once because the condition is checked after each iteration.
Syntax:
do
{
// Code to execute at least once
} while (condition);
Example:
using System;
public class DoWhileExample
{
public static void Main()
{
int number;
do
{
Console.Write("Enter a positive number (0 to exit): ");
number = int.Parse(Console.ReadLine());
Console.WriteLine("You entered: " + number);
} while (number != 0);
}
}
In this example:
- The
do
block executes once, regardless of thenumber
‘s initial value. - The loop continues as long as the entered
number
is not zero.
4. while
Loop with break
and continue
break
: Exits the loop entirely.continue
: Skips the current iteration and moves to the next one.
Example using break
:
using System;
public class BreakExample
{
public static void Main()
{
int count = 1;
while (count <= 10)
{
if (count == 5)
{
break; // Exit loop when count equals 5
}
Console.WriteLine("Count: " + count);
count++;
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Here, the break
statement exits the loop when count
reaches 5.
Example using continue
:
using System;
public class ContinueExample
{
public static void Main()
{
int count = 0;
while (count < 10)
{
count++;
if (count % 2 != 0)
{
continue; // Skip odd numbers
}
Console.WriteLine("Even count: " + count);
}
}
}
Output:
Even count: 2
Even count: 4
Even count: 6
Even count: 8
Even count: 10
In this example:
continue
skips the current iteration whencount
is odd, so only even numbers are printed.
5. Infinite while
Loop (and How to Avoid Them)
An infinite loop happens when the condition in the while
statement never becomes false
. While sometimes useful, infinite loops can cause a program to become unresponsive if not handled properly.
Example of Infinite Loop:
using System;
public class InfiniteLoopExample
{
public static void Main()
{
int counter = 1;
while (true) // Infinite loop
{
Console.WriteLine("Iteration: " + counter);
counter++;
if (counter > 5)
{
break; // Exits the loop to prevent infinite iteration
}
}
}
}
In this example:
- The
while (true)
creates an infinite loop. - The
break
statement stops the loop oncecounter
exceeds 5, preventing it from running forever.
Common Mistake Causing Infinite Loops:
Forgetting to update the loop variable or incorrectly setting the loop condition can lead to infinite loops.
using System;
public class InfiniteLoopMistake
{
public static void Main()
{
int counter = 1;
// This will be an infinite loop if 'counter++' is commented out.
while (counter <= 5)
{
Console.WriteLine("Iteration: " + counter);
// counter++; Uncommenting this will make the loop finite
}
}
}
In this example:
- If
counter++
is commented out,counter
will always be 1, causing an infinite loop.
Summary
The while
loop and do-while
loop are useful in cases where the number of iterations isn’t fixed but instead depends on a condition. Here’s a quick summary:
- Basic
while
loop: Repeats as long as the condition is true. - Using
while
with user input: Repeats until a specific user input is provided. do-while
loop: Executes the loop body at least once, regardless of the condition.break
andcontinue
: Manage the flow of the loop, withbreak
exiting andcontinue
skipping the current iteration.- Infinite loop: Created with
while (true)
or by mistake, usually needsbreak
to stop it safely.