๐ŸŽ“ A1Learner
๐Ÿ”

C++ For Loop

A for loop is a loop that repeats a block with a counter in its header. The header holds the start, the condition, and the change.

Counting from zero

The counter starts at 0. The loop stops before the counter reaches 5.

#include <iostream>

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

Stepping by two

The change part adds 2 after each run. The counter prints even numbers only.

#include <iostream>

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

Adding in a for loop

The total starts at 0. Each run adds the counter to the total.

#include <iostream>

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

Example

#include <iostream>

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

Key points

  • The for keyword starts the loop.
  • The header holds a start, a condition, and a change.
  • The start part runs once at the beginning.
  • The condition is checked before each run.
  • The change part runs after each run.

In this example, the counter starts at 2. The change part adds 2 after each run. The loop prints the even numbers up to 10.

Note

A for loop suits a count with a known start and end.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

Which part of a for header runs after each run?