capypad
0 day streak
cpp / beginner
Snippet

For Loops: Iteration with Known Count

A for loop repeats a block of code a specific number of times. It has three parts: initialization (int i = 0), condition (i < 5), and increment (i++). The loop runs as long as the condition is true, and the increment happens after each iteration.

snippet.cpp
cpp
1
2
3
4
5
6
7
#include <iostream>
int main() {
for (int i = 0; i < 5; i++) {
std::cout << "Iteration: " << i << std::endl;
}
return 0;
}
Breakdown
1
for (int i = 0; i < 5; i++)
Header: initializes counter, checks condition, increments after each iteration
2
int i = 0
Initialization: creates variable i and sets it to 0
3
i < 5
Condition: loop continues while i is less than 5
4
i++
Increment: adds 1 to i after each iteration
5
std::cout << "Iteration: " << i
Prints the current iteration number