cpp / beginner
Snippet
For Loops: Counting with Precision
A for loop has three parts: initialization (int i = 1), condition (i <= 5), and update (i++). The loop runs as long as the condition is true. The first loop counts from 1 to 5, the second counts backward from 10 in steps of 2.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>int main() {std::cout << "Counting from 1 to 5:" << std::endl;for (int i = 1; i <= 5; i++) {std::cout << i << std::endl;}std::cout << "\nCountdown:" << std::endl;for (int i = 10; i > 0; i -= 2) {std::cout << i << std::endl;}return 0;}
Breakdown
1
for (int i = 1; i <= 5; i++)
Loop header: start at 1, continue while <= 5, increment by 1 each iteration
2
std::cout << i << std::endl;
Prints current value of i each loop iteration
3
for (int i = 10; i > 0; i -= 2)
Loop that starts at 10, counts down while > 0, decrements by 2