09
Lesson 9 of 35 · Control Flow

Loops & Iteration

Loops let you repeat code without writing it multiple times. C# provides four loop constructs: for, while, do-while, and foreach. This lesson covers all four plus break, continue, and infinite loop patterns.

for Loop

The for loop is perfect when you know the number of iterations in advance. It has three parts: initialiser, condition, and iterator—all optional.

for loop examples ForLoop.cs
// Count up
for (int i = 0; i < 5; i++)
    Console.Write(i + " "); // 0 1 2 3 4

Console.WriteLine();

// Count down
for (int i = 10; i >= 1; i--)
    Console.Write(i + " "); // 10 9 8 ... 1

Console.WriteLine();

// Multiplication table
for (int r = 1; r <= 3; r++)
    for (int c = 1; c <= 3; c++)
        Console.Write($"{r*c,4}");

while & do-while Loops

Use while when the number of iterations is unknown and you want to check the condition before the first iteration. Use do-while to guarantee at least one execution.

while examples While.cs
// while — reads until user types 'quit'
string input = "";
while (input != "quit")
{
    Console.Write("Enter command: ");
    input = Console.ReadLine() ?? "";
}

// do-while — menu loop
int choice;
do
{
    Console.WriteLine("1. Start  2. Settings  3. Exit");
    choice = int.Parse(Console.ReadLine() ?? "0");
} while (choice != 3);

foreach Loop

The foreach loop iterates over any IEnumerable collection—arrays, lists, strings, and more. The loop variable is read-only; you cannot assign to it inside the loop.

foreach examples ForEach.cs
string[] fruits = { "apple", "banana", "cherry" };

foreach (string fruit in fruits)
    Console.WriteLine(fruit.ToUpper());

// foreach over a string (iterates characters)
foreach (char c in "Hello")
    Console.Write(c + "-"); // H-e-l-l-o-

break & continue

break exits the loop immediately. continue skips the rest of the current iteration and jumps to the next.

break and continue BreakContinue.cs
for (int i = 0; i < 10; i++)
{
    if (i == 3) continue; // skip 3
    if (i == 7) break;    // stop at 7
    Console.Write(i + " "); // 0 1 2 4 5 6
}