4.2 Extending the for Statement

You do not have to increment the loop control variable by 1 each time. It is also possible to count backwards or by values other than 1. To count backwards you just need to add the word decreasing as this example does:

for decreasing i : 10 .. 6
   put "i = ", i
end for

The output would be:

i = 10
i = 9
i = 8
i = 7
i = 6

To count by something other than ones you just need to add the word by followed by what you want to count by. This example prints cubes for every fourth value of count ranging from -8 to 14 (so 12 would be the last value used).

for count : -8 .. 14 by 4
   put count ** 3
end for 

This produces:

-512
-64
0
64
512
1728


Exercise 4.2

  1. For each fragment, state the number of times that the body of the for statement will be performed.
    1. for decreasing count : 20 .. -20
      .
      .
    2. var bound : int := -100
      for decreasing index : bound .. bound div 4
      .
      .
    3. var a : int := 3
      for decreasing lcv : a * 5 .. a div 5
      .
      .
    4. for decreasing i : 1 .. 10
      .
      .
    5. for decreasing i : 100 .. 50 by 5
      .
      .
  2. The program shown has a number of errors. Correct them and then determine the output of the corrected program.

    var x : real
    for x := 10 .. 1
       put This is step ..
    endfor
    put x 
  3. Trace the program shown below with input of 763
    const width : int := 5
    var divisor, quotient, remainder : int
    
    divisor := 1
    for position : 1 .. width -1
       divisor := divisor * 10
    end for
    
    get remainder
    
    for decreasing position : width .. 1
       quotient := remainder div divisor
       put quotient ..
       remainder := remainder mod divisor
       divisor := divisor div 10
    end for
    put "" 
  4. Assuming the the variables x and y have been declared as type int, write for statements that will print values of the function y = 2x + 5 for the indicated values of x.
    1. 6, 5, 4, ..., 0
    2. -7, -5, -3, ..., 7
    3. 0, 3, 6, ..., 30
    1. 50, 45, 40, ..., 5
    2. -15, -10, -5, ..., 10
    3. 40, 36, 32, ..., 8