CodeBlanks Logo Icon CodeBlanks

The for loop

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

The for loop

When you need a fixed number of iterations you use the for loop. It has three parts: initialization, condition and increment. for (int i = 0; i < 5; i++) { std::cout << i; } starts i at zero, repeats while i is below 5 and increases i by one each step.

The initialization runs only on the first iteration; the condition is checked at the start of every iteration; the increment is applied at the end. The loop body goes inside braces and can hold several statements.

The loop variable

The variable such as i in a for loop is called the loop variable. It is usually declared as int and lives only inside the loop. After the loop ends i is no longer accessible from outside.

The counter typically starts at 0 because arrays and vectors are also 0-indexed. The increment is usually i++ (increase by one) or i += 2 (increase by two). A decreasing loop is also possible: for (int i = 5; i > 0; i--).

Practice Print 0 to 4

Use a for (int i = 0; i < 5; i++) loop to print the numbers from 0 to 4 with std::cout << i; on a single line. The output must be 01234.

Starter code

main.cpp
#include <iostream>

int main() {
    // Print 0 to 4
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    for (int i = 0; i < 5; i++) {
        std::cout << i;
    }
    std::cout << std::endl;
    return 0;
}

Expected output

01234

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many times does for (int i = 0; i < 3; i++) run?

main.cpp
for (int i = 0; i < 3; i++) { ... }
  • 2 times
  • 4 times
  • 3 times Correct answer
  • Forever

Explanation: i = 0, 1, 2 means 3 iterations.

2 Write the for initialization

Question
for (____; i < 5; i++) { std::cout << i; }
Answer
for (int i = 0; i < 5; i++) { std::cout << i; }

Explanation: int i = 0 declares the type and the initial value.

3 Match each for part to its role

Term Meaning
int i = 0 Initialization
i < 5 Condition
i++ Increment
{ ... } Body

All lessons in Beginner