For

From Progzoo
Jump to: navigation, search

We can run over a sequence of values using a for loop.

Counting Up

The for loop can be used to run through a sequence of

integers.


[Font] [Default] [Show] [Resize] [History] [Profile]

Counting Down

You can start at a high number and count down.

[Font] [Default] [Show] [Resize] [History] [Profile]

Using Bigger Steps

You don't have to go up by one each time. In this example we go up by 2 each step and miss the odd numbers.

[Font] [Default] [Show] [Resize] [History] [Profile]

Using a Fractional Increment

You can use a fraction as the increment however this can be confusing because rounding errors can make it difficult to predict if the final loop will happen.

Notice that in this example the loop would happen 6 times if the calculations were exact. However because of rounding errors the seventh iteration occurs: d should be 2 and the loop should stop, however d is only 1.9999999999999998 and so the the seventh iteration does occur.


[Font] [Default] [Show] [Resize] [History] [Profile]