For Loop

Count through a range of numbers, or through an array's indexes forward, backward or in steps, with C#'s for loop.

Novice · C# · Updated

After this lesson you can

  • Repeat code a set number of times with a for loop
  • Loop through an array by index, forward or backward

Key takeaways

  • A for loop's start runs once, its condition is checked before every iteration, and its step runs after every iteration.
  • To visit every element, count from 0 while i < names.Length. With <=, the last iteration asks for an element that isn't there.
  • To go backward, start at Length - 1 and use i-- while i >= 0; to skip, step with i += 2.
  • To add up an array, start a total at 0 and add each element to it.
  • A for loop can fill an array as well as read it: evens[i] = (i + 1) * 2;.

A for loop is the loop for counting. When you know how many times to repeat, or you want to visit an array's elements by their index, for keeps everything about the counting in one line.

The three parts

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine("Lap " + i);
}
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5

The parentheses hold three parts, separated by semicolons:

Part Here When it runs
Start int i = 1 Once, before the loop begins. It creates the loop counter.
Condition i <= 5 Before every iteration. The loop runs while it's true.
Step i++ After every iteration. Here it adds 1 to the counter.

It does exactly what this while loop does, with the counting gathered in one place, so it's hard to forget the step:

int i = 1;
while (i <= 5)
{
    Console.WriteLine("Lap " + i);
    i++;
}

The counter is usually called i, for index. It exists only inside the loop.

Looping through an array

Indexes run from 0 to Length - 1, which is exactly what a for loop can count through:

string[] names = { "Alice", "Bob", "Charlie" };

for (int i = 0; i < names.Length; i++)
{
    Console.WriteLine(i + ": " + names[i]);
}
0: Alice
1: Bob
2: Charlie

Use i < names.Length, not <=. With <=, the last iteration would ask for names[3], which isn't there.

Adding things up

A very common pattern: start a total at 0, and add each element to it.

int[] scores = { 21, 14, 35, 28 };
int total = 0;

for (int i = 0; i < scores.Length; i++)
{
    total += scores[i];
}

Console.WriteLine("Total: " + total);
Console.WriteLine("Average: " + (double)total / scores.Length);
Total: 98
Average: 24.5

Other steps

The step can be anything. Count backward with i--, or jump with i += 2:

string[] names = { "Alice", "Bob", "Charlie", "Diana", "Eve" };

Console.WriteLine("Backward:");
for (int i = names.Length - 1; i >= 0; i--)
{
    Console.WriteLine(names[i]);
}

Console.WriteLine("Every other:");
for (int i = 0; i < names.Length; i += 2)
{
    Console.WriteLine(names[i]);
}
Backward:
Eve
Diana
Charlie
Bob
Alice
Every other:
Alice
Charlie
Eve

Backward starts at the last index, Length - 1, and keeps going while i >= 0.

Filling an array

A for loop can write to an array as well as read it. This fills an array with the first five even numbers:

int[] evens = new int[5];

for (int i = 0; i < evens.Length; i++)
{
    evens[i] = (i + 1) * 2;
}

Console.WriteLine(evens[0] + " " + evens[1] + " " + evens[4]);
2 4 10

Check yourself

2 questions to try on the lesson page.

So what

for puts the start, the stopping point and the step of a count in one line, which makes it the natural loop for numbered things, and arrays are numbered things.

Key terms

Cheat sheets