C# For Loop

C# For Loop

When you know exactly how many times you want to loop through a block of code, the for loop is a much cleaner option than a while loop. It condenses the initialization, condition check, and increment step into a single line.


The for Loop Syntax

for (statement 1; statement 2; statement 3) 
{
  // code block to be executed
}

For Loop Example

using System;

class Program { static void Main() { // This prints numbers 0 to 4 for (int i = 0; i < 5; i++) { Console.WriteLine(i); } } }


The foreach Loop

C# offers an incredible loop designed specifically to loop through arrays and collections: the foreach loop. It is cleaner and prevents "index out of bounds" errors.

Foreach Loop Example

using System;

class Program { static void Main() { // An array of cars string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; foreach (string i in cars) { Console.WriteLine(i); } } }

We will cover arrays in much more detail shortly, but as you can see, foreach makes reading through a list of items very simple!


Exercise

?

Which loop is specifically designed to easily read through an array?