cpp / beginner
Snippet
For Loops: Iterating a Known Number of Times
A for loop repeats a block of code a specific number of times. It has three parts: initialization (int i = 0), a condition (i < 5), and an increment (i++). The loop runs as long as the condition is true.
snippet.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>using namespace std;int main() {for (int i = 0; i < 5; i++) {cout << "Iteration number: " << i << endl;}return 0;}
Breakdown
1
for (int i = 0; i < 5; i++)
The loop header: creates a counter variable i, checks if i is less than 5, and increments i after each iteration
2
cout << "Iteration number: " << i << endl;
Prints the current iteration number to the console
3
}
Marks the end of the loop body - the code inside will repeat