cpp / beginner
Snippet
Repeating Code with for Loops
A for loop repeats a block of code a specific number of times. It has three parts inside the parentheses: initialization (int i = 0) sets the starting value, condition (i < 5) determines when to stop, and increment (i++) runs after each iteration. The loop continues as long as the condition is true. Here, it prints numbers from 0 to 4, giving us 5 total iterations.
snippet.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>int main() {for (int i = 0; i < 5; i++) {std::cout << "Iteration number: " << i << std::endl;}return 0;}
Breakdown
1
for (int i = 0; i < 5; i++) {
Loop header: init; condition; increment
2
int i = 0
Initialization: creates counter variable i set to 0
3
i < 5
Condition: loop runs while i is less than 5
4
i++
Increment: increases i by 1 after each iteration
5
std::cout << "Iteration number: " << i << std::endl;
Body: runs each iteration, prints current i value