C# ยท Chapter 19 of 46

C# For & Foreach Loops

A for loop is used when you know how many times you want to repeat something, combining initialization, condition, and increment in one line. It's commonly used to loop a fixed number of times or iterate over indexed collections.

A foreach loop is used to iterate over each element in a collection, like an array or list, without needing to manage an index manually.

Syntax
for (init; condition; increment) {
  // code
}

foreach (var item in collection) {
  // code
}

for loop

A for loop has three parts: initialization (runs once), condition (checked each iteration), and increment (runs after each iteration). This makes it ideal for counting loops.

foreach loop

A foreach loop automatically goes through each item in a collection, assigning it to a loop variable, which is simpler and safer than manually indexing.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    for (int i = 0; i < 3; i++) {
      Console.WriteLine(i);
    }
  }
}
Output
0
1
2

The loop starts at 0, runs while i < 3, and increments i after each pass.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    string[] fruits = { "apple", "banana", "cherry" };
    foreach (string fruit in fruits) {
      Console.WriteLine(fruit);
    }
  }
}
Output
apple
banana
cherry

foreach automatically visits each element in the fruits array.

Key points

  • A for loop has initialization, condition, and increment sections.
  • foreach iterates over each item in a collection automatically.
  • foreach does not let you modify the collection's structure while looping.
  • break exits a loop early, and continue skips to the next iteration.
๐Ÿ’ก Note: Use foreach when you just need each item's value, and for when you need index-based control.

๐Ÿ“ Quick Quiz

1. What are the three parts of a for loop?

2. What does foreach iterate over?

3. Which statement skips to the next loop iteration?