Loading lessons...
For & Foreach Loops
For & Foreach Loops
The for loop
The for loop packs three things into one line: a start value, a condition, and an increment:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
This prints 0 1 2 3 4.
Parts of the loop:
- Statement 1 -
int i = 0: runs once at the start. - Statement 2 -
i < 5: the condition, checked before each run. - Statement 3 -
i++: runs after each loop, updating the counter.
The foreach loop
foreach is made for looping through collections like arrays. It's simpler - no counter needed:
string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };
foreach (string car in cars)
{
Console.WriteLine(car);
}
Each element of the collection is assigned to car in turn.
foreach vs for
foreach- read every element of a collection, clean and safe.for- more control when you need indexes, counting, or skipping.
Nested loops
You can put a loop inside a loop. The inner loop completes fully for each run of the outer one.
TL;DR
for= start value + condition + increment.foreachiterates collections without a counter.foreachis ideal for reading every element of an array.