Skip to content

C# - Loops

In programming, we often need to repeat an action multiple times. Instead of writing the same code over and over, we use loops. A loop is a control structure that allows you to execute a block of code repeatedly as long as a certain condition is met.

The basic idea of a loop can be visualized as a cycle:

+-------------------------+
| Is the condition true? |
+-----------+-------------+
| Yes
+---------v---------+
| Execute loop body |
+---------+---------+
|
+---------v---------+
| Update state | (e.g., increment counter)
+---------+---------+
|
+-----------+ (Go back and check condition again)
+-----------+-------------+
| No |
+-----------v-------------+
| Exit loop |
+-------------------------+

C# provides several types of loops, each suited for different scenarios.

Loop TypeBest For
for loopWhen you know the exact number of iterations (e.g., repeat 10 times).
foreach loopIterating over all elements in a collection (like a list or an array).
while loopWhen you want to loop as long as a condition is true, and the number of iterations is unknown beforehand.
do-while loopSimilar to a while loop, but guarantees the loop body is executed at least once.

The for loop is ideal for when you need to execute a block of code a specific number of times. It consists of three parts: an initializer, a condition, and an iterator.

using System;
// Print numbers from 1 to 5
for (int i = 1; i <= 5; i++)
{
// i = 1: initializer (runs once at the start)
// i <= 5: condition (checked before each iteration)
// i++: iterator (runs after each iteration)
Console.WriteLine($"Current number: {i}");
}

Output:

Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5

The foreach loop provides a simple, clean way to iterate over the elements of a collection, such as an array, list, or dictionary. It is often the most readable choice for this task.

using System;
using System.Collections.Generic;
var fruits = new List<string> { "Apple", "Banana", "Cherry" };
// Loop through each element in the 'fruits' list
foreach (var fruit in fruits)
{
Console.WriteLine($"I like {fruit}s!");
}

Output:

I like Apples!
I like Bananas!
I like Cherrys!

A while loop repeatedly executes a block of code as long as a given condition is true. The condition is checked before each iteration.

using System;
int countdown = 3;
while (countdown > 0)
{
Console.WriteLine($"{countdown}...");
countdown--; // It's crucial to change the variable to avoid an infinite loop
}
Console.WriteLine("Lift off!");

Output:

3...
2...
1...
Lift off!

The do-while loop is similar to the while loop, but the condition is checked after the loop body has executed. This guarantees that the loop will run at least once.

using System;
string? input;
do
{
Console.WriteLine("Enter 'exit' to quit:");
input = Console.ReadLine();
// ... process input ...
} while (input != "exit");
Console.WriteLine("Program terminated.");

You can change a loop’s normal execution flow using control statements.

  • break: Immediately terminates the innermost loop and transfers control to the statement following the loop.
  • continue: Skips the rest of the current iteration and proceeds to the next iteration of the loop.
// Example of 'break' and 'continue'
for (int i = 1; i <= 10; i++)
{
if (i % 2 != 0)
{
continue; // Skip odd numbers
}
if (i > 8)
{
break; // Exit the loop if number is greater than 8
}
Console.WriteLine(i); // This line only runs for even numbers <= 8
}

Output:

2
4
6
8

An infinite loop occurs when a loop’s condition never becomes false. While sometimes intentional for services that run continuously, they are often a bug. To create an intentional infinite loop, while(true) is more readable than for(;;).

In real-world applications like background services, an infinite loop should be combined with a mechanism for graceful shutdown, such as a CancellationToken, to allow the loop to be stopped safely.