cpp / beginner
Snippet
For Loops: Iterating with Known Count
For loops are ideal when you know exactly how many times code should repeat. They combine initialization, condition checking, and increment into a single line. This example counts from 0 to 4, printing each number. The loop variable i starts at 0, continues while i is less than 5, and increments after each iteration.
snippet.cpp
1
2
3
4
5
6
7
#include <iostream>int main() {for (int i = 0; i < 5; i++) {std::cout << "Count: " << i << std::endl;}return 0;}
Breakdown
1
for (int i = 0; i < 5; i++)
Loop header: initialize i to 0, check if i<5, increment i after each iteration
2
int i = 0
Declaration and initialization of loop counter variable
3
i < 5
Condition that must be true for loop to continue
4
i++
Post-iteration increment (shorthand for i = i + 1)
5
std::cout << "Count: " << i << std::endl;
Prints current count value to console each iteration