Ad space (banner)
Lesson 5 / 20

Loops (for statements)

This lesson covers repeating logic in C++ using a for loop. It's for anyone searching "C++ for loop usage."

The form for (initialization; condition; update) { ... } repeats logic a fixed number of times. Using a counter variable, typically named i, is the standard convention.

The example uses for (int i = 1; i <= 5; i++) to print the numbers 1 through 5 in order.

A common early mistake is the loop running one time too many or too few (an off-by-one error), depending on exactly how the condition is written. Paying close attention to the difference between i <= 5 and i < 5, and getting the intended count exactly right, matters.

In real projects, for loops are used constantly โ€” processing every element of an array, or repeating a calculation a fixed number of times.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C++ directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)