The for loop is probably the most commonly used loop in C#. It is perfect
when you know exactly how many times you want to repeat something.
Anatomy of a for Loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// Output: 0 1 2 3 4
A for loop has three parts separated by semicolons:
- Initialization:
int i = 0โ runs once before the loop starts - Condition:
i < 5โ checked before each iteration; loop stops when false - Iterator:
i++โ runs after each iteration
The variable i is called the loop counter. By convention, it is always named
i, but you can name it anything you want.
Counting Backwards
for (int i = 10; i >= 1; i--)
{
Console.Write(i + " ");
}
// Output: 10 9 8 7 6 5 4 3 2 1
Just change the initial value, the condition, and the iterator direction. Simple.
The foreach Loop
The foreach loop is designed for iterating over collections like arrays and lists.
It is cleaner and less error-prone than a regular for loop when you just need to
look at each item:
string[] cities = { "Kano", "Lagos", "Abuja", "Port Harcourt" };
foreach (string city in cities)
{
Console.WriteLine($"I want to visit {city}");
}
You do not need to worry about indexes or off-by-one errors. foreach handles
all of that for you. It goes through each item in the collection, one by one, until
there are no more items.
Nested Loops
You can put loops inside loops. This is useful when you are working with tables or multi-dimensional data:
for (int row = 1; row <= 3; row++)
{
for (int col = 1; col <= 3; col++)
{
Console.Write($"{row}{col} ");
}
Console.WriteLine();
}
// Output:
// 11 12 13
// 21 22 23
// 31 32 33
The inner loop completes all its iterations before the outer loop moves to the next iteration. So for each row, you get all three columns.
Which Loop Should You Use?
- Use
forwhen you know how many times to loop - Use
foreachwhen you want to go through each item in a collection - Use
whilewhen the number of iterations depends on a condition - Use
do-whilewhen you need the code to run at least once