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.
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.
using System;
class Program {
static void Main() {
for (int i = 0; i < 3; i++) {
Console.WriteLine(i);
}
}
}0
1
2The loop starts at 0, runs while i < 3, and increments i after each pass.
using System;
class Program {
static void Main() {
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
}
}apple
banana
cherryforeach 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.
