Lesson 9 · 9 of 20
for and range-based for · C++
Count with the classic C++ for loop, go through collections with the range-based for, and nest loops to build a table.

The classic `for` puts three parts in brackets: the start (int i = 1), the condition (i <= 5) and the step (i++). It is the loop for counting, here the 7 times table. The variable i only exists inside the loop.
The step can be anything: n += 2 goes through the even numbers up to 100, adding them up in sum. When the body is a single statement, no braces are needed.
The range-based `for`, for (double t : temps), visits every element of a collection without indices: on each round t takes one value. temps is a fixed-size array inherited from C; the next lesson introduces std::vector, which is far more flexible.
A std::string is a collection too, of characters: the loop looks at each char in programming and counts the vowels.
Nested loops sit one inside another: for each row, the inner loop goes through the four columns, and '\t' lines them up as a table.
Code · main.cpp
#include <iostream>#include <string>int main() { // for (start; condition; step): the classic counting loop. for (int i = 1; i <= 5; i++) { std::cout << "7 x " << i << " = " << 7 * i << '\n'; } // Adding up inside a loop, in steps of 2. int sum = 0; for (int n = 2; n <= 100; n += 2) sum += n; std::cout << "2 + 4 + ... + 100 = " << sum << '\n'; // Range-based for: goes through every element of a collection. double temps[] = {18.5, 21.0, 24.5, 19.0}; double total = 0; for (double t : temps) total += t; std::cout << "Average temperature: " << total / 4 << '\n'; // A string is a collection of characters. int vowels = 0; for (char c : std::string("programming")) if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') vowels++; std::cout << "Vowels in \"programming\": " << vowels << '\n'; // Nested loops: a small multiplication grid. for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 4; col++) std::cout << row * col << '\t'; std::cout << '\n'; } return 0;}Output · c++ -std=c++17 main.cpp -o main && ./main
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 2 + 4 + ... + 100 = 2550 Average temperature: 20.75 Vowels in "programming": 3 1 2 3 4 2 4 6 8 3 6 9 12
Key points
for (start; condition; step)is for counting.- The step can be
i++,i--,i += 2... for (type x : collection)visits every element.- A string can be walked character by character.
- A loop inside another goes through rows and columns.
Exercise
Print the full times tables from 1 to 9 with two nested for loops and, with a range-based for over the array {12, 7, 30, 5}, find the largest of those numbers.