Lesson 8 — Repetition

Loops

C# loops are nearly identical to Java's with one distinction: foreach is a first-class keyword that works on any IEnumerable, making it the idiomatic way to iterate collections.

CSHARP — for loops
// for loop:
for (int i = 1; i <= 5; i++)
    Console.WriteLine($"Iteration {i}");

// Counting down:
for (int i = 10; i >= 1; i--)
    Console.Write($"{i} ");
Console.WriteLine("Lift off!");

// Nested loops:
for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++)
        Console.Write($"{row * col,4}");
    Console.WriteLine();
}

foreach — The Idiomatic C# Loop

foreach works on any type implementing IEnumerable<T> — arrays, lists, dictionaries, strings, database result sets, and more. Use it whenever you need all elements and do not need the index.

CSHARP — foreach, while, break/continue
string[] names = { "Thandi", "Sipho", "Lerato", "Bongani" };

// foreach — clean, no index management:
foreach (string name in names)
    Console.WriteLine($"Hello, {name}!");

// for — use when you need the index:
for (int i = 0; i < names.Length; i++)
    Console.WriteLine($"{i + 1}. {names[i]}");

// while loop:
int balance = 1000;
while (balance > 0) {
    Console.WriteLine($"Balance: R{balance}");
    balance -= 250;
}

// break and continue:
foreach (int n in new[] { 1,2,3,4,5,6,7,8,9,10 }) {
    if (n % 2 == 0) continue; // skip even
    if (n > 7) break;          // stop after 7
    Console.Write($"{n} ");    // 1 3 5 7
}

Practice Task

Your Turn

Create a string array of 5 learner names. Use foreach to print each with a greeting. Use for with index to print each numbered. Use a while loop to sum their marks (use a parallel int array). Use a do-while to simulate 3 login attempts.

Common Mistakes

  • Modifying a collection inside foreach — throws InvalidOperationException. Iterate a copy or use a for loop.
  • foreach gives a copy of value types — modifying the loop variable does not affect the original.
  • Infinite while — always verify the condition moves toward false.
  • Off-by-one: i < length vs i <= length.

Professional Tip

When you have a choice between for and foreach, prefer foreach — it is more readable, safer (no index arithmetic), and works on any collection type not just arrays.

Mini Quiz

Which loop iterates all elements without managing an index?