For Loop
Computers are good at doing the same job many times. A loop runs a block of code again and again. Use the for loop when you know how many times the code should run: 5 times, or once for every number from 1 to 100.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << "\n";
return 0;
}
Output:
1 2 3 4 5
The first line of the loop has three parts, separated by semicolons:
for (int i = 1; i <= 5; i++)
--------- ------ ---
start condition step
This is the order C++ follows:
- Start:
int i = 1runs once, before anything else. It creates the counter variablei. - Condition: C++ checks
i <= 5. If it is false, the loop ends. - Body: the code in the braces runs.
- Step:
i++adds 1 toi. Then C++ goes back to step 2.
So the body ran with i equal to 1, 2, 3, 4 and 5. When i became 6, the condition was false and the loop stopped. Programmers often name the counter i, and everyone reads it as "the loop counter".
Using the counter
The counter is a normal variable, so you can use it in the body. This loop adds the numbers from 1 to 100:
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
cout << "Sum: " << sum << "\n";
Output:
Sum: 5050
The step can also go down. i-- takes 1 away from i, so this loop counts backwards:
for (int i = 3; i >= 1; i--) {
cout << i << " ";
}
cout << "\n";
Output:
3 2 1
Check the condition carefully
i <= 5 and i < 5 look almost the same, but they run a different number of times:
for (int i = 1; i < 5; i++) {
cout << i << " ";
}
cout << "\n";
Output:
1 2 3 4
With <, the body ran only 4 times, because 5 is not less than 5. Running a loop one time too many or one time too few is a very common bug. Each time you write a condition, check the first and the last value.
In the exercise, read a number n and print the numbers from 1 to n.