
Would you write the same line 100 times? No. A for loop counts and repeats for you.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl;
return 0;
}> what you see
1 2 3 4 5
//LINE BY LINE
Watch it run
The start runs once, before the loop begins.
The three parts
Inside the brackets of a for there are three parts, separated by semicolons.
for (int i = 0; i < 5; i++) {
// ───────── ───── ───
// 1 эхлэл 2 нөхцөл 3 алхам
cout << i << " ";
}> what you see
0 1 2 3 4
- 1.Start — runs once, before the loop begins.
- 2.Condition — checked before each turn; the loop stops when it becomes false.
- 3.Step — runs at the end of every turn.
Counting down, and skipping
for (int i = 5; i >= 1; i--) cout << i << " "; // 5 4 3 2 1
for (int i = 0; i <= 10; i += 2) cout << i << " "; // 0 2 4 6 8 10i < 5 runs 5 times (0–4); i <= 5 runs 6 times (0–5). Off-by-one is the classic loop bug.
Looping over a whole collection
When you do not need the index — only the values — there is a shorter form.
int marks[5] = {5, 3, 9, 1, 7};
for (int m : marks) {
cout << m << " ";
}> what you see
5 3 9 1 7