cpp / beginner
Snippet
For Loops: Counting and Iterating
A for loop executes code repeatedly based on three parts: initialization (run once at start), condition (checked before each iteration), and increment (run after each iteration). Here, i starts at 0 and the loop runs while i is less than 5.
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: init i=0, check i<5, increment i++ after each iteration
2
std::cout << "Count: " << i << std::endl;
Outputs the current value of i each time the loop body executes