CodeBlanks Logo Icon CodeBlanks

The for loop

C# course · Beginner · Lesson 42/116

Learn to write counted loops with for and use a counter.

The for loop

For tasks that repeat a known number of times you use the for loop. It has three parts: init, condition and update. for (int i = 0; i < 5; i++) { ... } runs the block 5 times; i starts at 0 and grows by one each step.

The counter usually starts at 0; this fits well with arrays. The condition is checked before each step; when it is false the loop ends. i++ runs after each step.

Counter and accumulation

Inside a for loop you can accumulate a variable to compute sums or products. The pattern int sum = 0; for (...) sum += i; gives the sum of numbers from 1 to N.

It is important to reset the accumulator BEFORE the loop; otherwise the old value stays. sum += i is a shortcut for sum = sum + i and adds i to the current value each step.

Exercise Print 1 through 5

Use a for loop to print the numbers 1 through 5 (inclusive) with Console.WriteLine. The counter must start at 1 and the condition must be i <= 5.

Show example solution
Write for (int i = 1; i <= 5; i++) { Console.WriteLine(i); }
Example solution:
using System;

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

Test yourself

  1. How many lines does for (int i = 0; i < 3; i++) Console.WriteLine(i); print?

    for (int i = 0; i < 3; i++) Console.WriteLine(i);
    • 2 lines: 0, 1
    • 4 lines: 0, 1, 2, 3
    • 3 lines: 0, 1, 2
    • 1 line: 3
    Show answer

    3 lines: 0, 1, 2 — Correct. The condition holds for i = 0, 1, 2; it stops when i = 3.

  2. Complete the for header

    for (int i = 0; ____; i++)
    {
        Console.WriteLine(i);
    }
    Show answer
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine(i);
    }
  3. Match each for part to its meaning

    int i = 0
    Init
    i < 5
    Condition
    i++
    Update
    { ... }
    Loop body

All lessons in Beginner