When you know how many times to repeat, a for loop is the clearest choice. It puts the start, the condition and the step on one line:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "Hello number " << i << "\n";
}
return 0;
}Output
Hello number 1 Hello number 2 Hello number 3 Hello number 4 Hello number 5
The three parts inside the brackets, separated by semicolons:
int i = 1– start: runs once, before the loop begins.i <= 5– condition: checked before every round. The loop stops when it is false.i++– step: runs after every round.
Tip: Programmers usually call a simple counter
i(for index). It's fine to use it.
Counting in different ways
#include <iostream>
using namespace std;
int main() {
// Count from 0 to 4 (very common in C++)
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
cout << "\n";
// Count down
for (int i = 10; i >= 1; i--) {
cout << i << " ";
}
cout << "Lift off!\n";
// Count in steps of 5
for (int i = 0; i <= 25; i += 5) {
cout << i << " ";
}
cout << "\n";
return 0;
}Output
0 1 2 3 4 10 9 8 7 6 5 4 3 2 1 Lift off! 0 5 10 15 20 25
A times table
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= 5; i++) {
cout << n << " x " << i << " = " << n * i << "\n";
}
return 0;
}Input (what the user types)
7
Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
Remember: A variable created inside the
forbrackets (likei) only exists inside that loop.