O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The for Loop

The classic loop construct is known as a counted loop, and the for loop is the only such construct provided by the C language. This is the equivalent of telling the computer that you want to execute the same block of code a set number of times. You can count up or down, in single steps or multiples of steps.

So you can loop from 1 to 10:

1    2    3    4    5    6    7    8    9    10

You can also loop from 10 to 1:

10    9    8    7    6    5    4    3    2    1

Or you can loop forwards or backwards, skipping every second number:

1    3    5    7    9

Note that even though the start and end points are the same (1 and 10, respectively), when you skip numbers, you loop fewer times. If you were to execute code on each of the numbers, you would only execute it five times, rather than 10. In the last ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required