5.2 — for loops

📘 Chapter 5⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Counting loops#

A for loop is the neatest way to repeat something a set number of times.

C++
for (int i { 1 }; i <= 5; ++i){    std::cout << i << ' ';}
Output
1 2 3 4 5

The three parts#

Inside ( ) there are three parts, split by ;:

  • int i { 1 } = start: make a counter. Runs once.
  • i <= 5 = check: keep going while this is true.
  • ++i = step: runs after each trip.

It does the same as this while loop, but tidier:

C++
int i { 1 };while (i <= 5){    std::cout << i << ' ';    ++i;}

Counting in other ways#

C++
for (int i { 0 }; i < 10; i += 2)   // 0 2 4 6 8for (int i { 10 }; i > 0; --i)      // 10 9 8 ... 1
Tip

Programmers usually start counting at 0 and use <: for (int i { 0 }; i < 5; ++i) runs 5 times: 0, 1, 2, 3, 4. You will see why in 8.1 — vector: a list that grows.

Example: times table#

C++
int n { 7 };for (int i { 1 }; i <= 10; ++i){    std::cout << n << " x " << i << " = " << n * i << '\n';}
Good habit

Use for when you know how many times to loop. Use while when you loop "until something happens".

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.