Loops let you run the same code multiple times without writing it over and over again.
Imagine printing the numbers 1 to 100. Without loops, you would need 100 Console.WriteLine()
statements. With loops, you need maybe 3 lines of code.
The while Loop
The while loop keeps running as long as its condition is true:
int count = 1;
while (count <= 5)
{
Console.WriteLine(count);
count++;
}
// Output: 1 2 3 4 5
Be very careful with while loops. If the condition never becomes false, you get
an infinite loop and your program hangs forever. Always make sure something
inside the loop changes the condition.
The do-while Loop
The do-while loop is similar to while, but it always runs at least once
because the condition is checked at the end:
int number;
do
{
Console.Write("Enter a positive number: ");
number = int.Parse(Console.ReadLine());
}
while (number <= 0);
Console.WriteLine($"You entered: {number}");
This is perfect for input validation. The code runs once, asks the user for input, and then checks if the input is valid. If not, it keeps asking until they provide a valid number.
Breaking Out of Loops
Sometimes you want to exit a loop before it finishes. Use the break statement:
int count = 1;
while (true) // This looks like an infinite loop!
{
if (count > 5)
{
break; // But we break out when count exceeds 5
}
Console.WriteLine(count);
count++;
}
// Output: 1 2 3 4 5
The while (true) pattern looks dangerous, but combining it with break
is actually a common and accepted practice. It makes the exit condition very clear.
Skipping Iterations
The continue statement skips the rest of the current iteration and moves to
the next one:
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; // Skip even numbers
}
Console.Write(i + " ");
}
// Output: 1 3 5 7 9
Think of continue as saying "skip this one, move on to the next."