3.2 for Loops and Counting
When the number of iterations is clear, a for loop is usually cleaner than a while loop. It writes the initialization, condition, and update on one line.
The basic for structure
A C++ for loop is written as for (init; condition; update). The condition is checked before each round, and the update runs after the loop body.
for (int i = 0; i < 5; i++) {
std::cout << i << " ";
}
std::cout << std::endl;
for (int i = 10; i < 15; i++) {
std::cout << i << " ";
}
std::cout << std::endl;
for (int i = 1; i < 10; i += 2) {
std::cout << i << " ";
}
std::cout << std::endl;Output:
0 1 2 3 4
10 11 12 13 14
1 3 5 7 9for (int i = start; i < stop; i += step) starts at start, increases by step, and stops before stop. In other words, stop is a "stop here" boundary, not the last value printed.
Counting a fixed number of times
To sum the integers from 1 to 100, let the loop variable go from 1 through 100.
int total = 0;
for (int i = 1; i <= 100; i++) {
total += i;
}
std::cout << "Sum of 1 to 100: " << total << std::endl;Output:
Sum of 1 to 100: 5050This makes the range of the loop variable i easier to see than with a while loop.
The Fibonacci sequence
The first two terms of the Fibonacci sequence are 1, 1. From the third term on, each term equals the sum of the previous two.
int n;
std::cin >> n;
if (n <= 0) {
std::cout << "Enter a positive integer." << std::endl;
} else if (n == 1) {
std::cout << 1 << std::endl;
} else {
int first = 1, second = 1;
std::cout << first << " " << second << " ";
for (int i = 3; i <= n; i++) {
int current = first + second;
std::cout << current << " ";
first = second;
second = current;
}
std::cout << std::endl;
}One possible run:
10
1 1 2 3 5 8 13 21 34 55The most important updates in the loop are these two lines:
first = second;
second = current;They slide the window forward by one so the next round keeps using the latest "previous two" terms.