C++20 sections · 1024 units
Open in Course

Counting with while

Using loops to count

Counting is the most common loop pattern. You initialize a counter variable, check if it is below a limit, and increment it after each iteration. Here is a counting loop: int i = 1; while (i <= 10) { cout << i << " "; i++; } prints 1 through 10.

The counter starts at 1 and the loop stops after printing 10. You control the step size by changing the increment. Using i += 2 counts by twos: 1, 3, 5, 7, 9. Using i-- counts down from your starting value.