cpp / beginner
Snippet
For Loops: Repeating Code a Specific Number of Times
A for loop repeats code when you know exactly how many times it should run. It has three parts: the starting point (int i = 0), the condition (i < 5), and the increment (i++). The variable i starts at 0, and each iteration increases it by 1 until i reaches 5, then the loop stops.
snippet.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++)
Loop header: initialize i to 0, check if i < 5, then increment i after each iteration
2
std::cout << "Iteration: " << i
Prints the current value of i with descriptive text
3
std::endl
Ends the line and flushes the output buffer