C++ For Loop

The for loop is the loop you reach for when you know exactly how many times you want to repeat something. It packs the three key parts of a counting loop, the start value, the condition, and the update, into a single tidy line. That makes counting loops shorter to write and easier to read at a glance.

The for loop

A for loop has three statements separated by semicolons inside its parentheses. The first sets up a starting value, the second is the condition tested before each pass, and the third updates the value after each pass.

Print numbers 0 through 4

#include <iostream>
using namespace std;

int main() {
  for (int i = 0; i < 5; i++) {
    cout << i << "\n";
  }
  return 0;
}
  • Statement 1 (int i = 0) runs once, before the loop starts.
  • Statement 2 (i < 5) is checked before every pass; the loop runs while it is true.
  • Statement 3 (i++) runs after each pass through the body.
Note: A variable declared inside the for statement, like i above, only exists inside the loop. Trying to use it after the loop ends will cause a compile error.

Counting in different steps

You are not limited to counting up by one. You can start anywhere, stop anywhere, and change the step. This loop prints only even numbers from 0 to 10 by adding 2 each time.

Even numbers with a step of 2

#include <iostream>
using namespace std;

int main() {
  for (int i = 0; i <= 10; i += 2) {
    cout << i << "\n";
  }
  return 0;
}
GoalFor loop header
Count 1 to 5for (int i = 1; i <= 5; i++)
Count down 5 to 1for (int i = 5; i >= 1; i--)
Every third numberfor (int i = 0; i < 30; i += 3)

Use a for loop whenever the number of repetitions is known or easy to calculate. If you only know the stopping condition but not the count, a while loop is often the clearer choice.

Exercise: C++ For Loop

What are the three clauses inside a traditional for loop's parentheses, in order?