Loops and Repetition


Loops

Computers are good at doing repetitive tasks. They don't complain even when they are asked to do the same thing thousands of times.

In the very early days of computers, long before modern computers were made, people wrote programs on long strips of paper tape. The programs were encoded as holes punched into the paper, and the paper tape was fed into the computer, which read it and performed the instructions on it one by one. To do the same thing over and over, people taped two ends of a paper tape together to make a loop, and let the loop go around and around.

Today, when a program performs a repetitive task, we still say that it is performing a loop. This chapter introduces one kind of loop, a while-loop.


While-loops

A problem faced by early programmers was to decide when to stop letting a loop go around, to cut the tape and start doing something else. Usually, they just counted how many times it went around.

A while-loop handles that problem by checking the value of an expression each time around the loop. If the expression has value true, it means to go around again. If the expression has value false, the loop ends.

In Cinnameg, a while-loop has the form

  While condition do
    statements to be repeated
  %While
where condition is an expression that produces true or false. Each time around the loop it tests whether the condition is true. If so, it performs the statements, and tests the condition again. It keeps doing that until it tests the condition and finds that the value is false. Then the loop is done, and the program continues with whatever comes after the while-loop.

For example, the following statements will show You are great. 10 times, on 10 separate lines.

  Let count = 0.
  While count < 10 do
    Displayln "You are great.".
    Relet count = count + 1.
  %While
The sequence of statements that is done repeatedly is called the loop body. Notice that, in the example shown, each time the loop body is done, variable count becomes one larger. Eventually, count will be 10. At that point, the condition count < 10 will be false, and the loop will be over.


Indentation

Indent the body of a while-loop about two spaces, to show that it belongs to the loop.

Do not indent what comes after the loop any more than the While line is indented. What comes after the loop is not part of the loop.


Hand simulation of a loop

After writing a loop, you will want to do a hand simulation to see whether it works. Show the variables, and show how each changes. For example, here is a loop that makes sum = 1 + 2 + 3 + 4 + 5. When the loop is finished, the value of sum is written out.

  Let count = 0.
  Let sum = 0.
  While count < 5 do
    Relet count = count + 1.
    Relet sum = sum + count.
  %While
  Displayln "sum = " ++ $(sum).
A hand simulation goes as follows. Struck out values are values that the variable had, but that were replaced.
count    sum
 0      0 
 1      1 
 2      3 
 3      6 
 4      10 
5    15
Now expression
count < 5
is false, so the loop ends, and this sequence of statements writes
sum = 15


Loop control variables

A loop generally has some variables, called its loop control variables, that are changed (at least sometimes) by the loop body. When you think about a loop, think about its loop control variables. Make sure that you initialize them, usually just before the loop. Make sure that the loop body updates them appropriately.

Here is another loop, this one making sum = 2 + 3 + 5 + 7 + 11, the sum of the prime numbers that are less than 12. Its loop control variables are count and sum. Notice that the loop control variables are created and given initial values just before the loop starts. Also notice that sum is only changed when count is a prime number. (We assume that function isPrime(n) is available, which yields true when n is a prime number.)

  Let count = 2.
  Let sum = 0.
  While count < 12 do
    If isPrime(count) then
      Relet sum = sum + count.
    %If
    Relet count = count + 1.
  %While
Here is a hand simulation of it, in stages. As a starting point, initialize the variables.
count    sum
2    0
Since count < 12, the program does the loop body. Since 2 is a prime number, count is added to sum. The next step is as follows.
count    sum
 2      0 
3    2
The count is still less than 12, so the loop goes through again. Since 3 is prime, we get the following.
count    sum
 2      0 
 3      2 
4    5
But 4 is not prime. The next time through the loop body, sum is not changed. When simulating a loop, it is convenient to copy the value of a loop control variable that does not change so that the rows are lined up, and you can see the values of the loop control variables at the top of the loop, right beside one another, and we do that here by striking out the old value and showing it exactly the same as it was.
count    sum
 2      0 
 3      2 
 4      5 
5    5
Continuing in this manner yields the following completed hand simulation.
count    sum
 2      0 
 3      2 
 4      5 
 5      5 
 6      10 
 7      10 
 8      17 
 9      17 
 10      17 
 11      17 
12    28
The program reaches the top of the loop with count = 12. At the point, it continues running just after the loop, since count < 12 is false. The loop ends with sum = 28.


Loops in functions and procedures

A function or procedure definition can contain a loop. For example, the following function sum(n) returns 1 + 2 + ... + n, as long as n is a positive integer.

  Define
    sum(n) = r |
      Let k = 1.
      Let r = 1.
      While k < n do
        Relet r = r + k.
        Relet k = k + 1.
      %While
  %Define


If or While?

Sometimes inexperienced programmers forget whether to write If of While in their programs. Here are some rules to remember.

  1. Use If when you want to do one action or another. You just want to make a decision. There is no repetition.

    Also use If when you might want to do an action and might not.

  2. Use While when you want to repeat something several times.

    Remember that there is no else for a while-loop. So do not write else after the loop. When the loop is done, the program continues running after the loop.


Problems

  1. [solve] Do a careful hand simulation of computation of sum(4) using the following definition of sum. Show how variables k and r change, and what the answer is.

      Define
        sum(n) = r |
          Let k = 1.
          Let r = 0.
          While k <= n do
            Relet r = r + k.
            Relet k = k + 1.
          %While
      %Define
    

  2. [solve] Do a careful hand simulation of computation of sum(0) using the following definition of sum. Show how variables k and r change, and what the answer is.

      Define
        sum(n) = r |
          Let k = 1.
          Let r = 0.
          While k <= n do
            Relet r = r + k.
            Relet k = k + 1.
          %While
      %Define
    

  3. [solve] A hunter leaves his camp and travels exactly fifty miles due south. Then he turns and travels exactly fifty miles due west. At that point, he shoots a bear. Then he travels exactly fifty miles due north, and ends up back at his camp. What color was the bear?

  4. [solve] This question requires some thought about how a while-loop works. Suppose you see the following program fragment, with part of it hidden from view (as some dots).

      Let k = 1.
      While k =/= 10 do
        ...
      %While
      Displayln k.
    
    When you run this, a value is displayed. Without seeing the body of the loop, can you say what was displayed?


Summary

A loop repeats some sequence of statements. The loop body is the sequence of statements that is repeated.

A while-loop is a kind of loop that repeats the statements until some condition is false.

Loop control variables are variables that the loop body changes. Be sure to initialize the loop control variables before the loop.

Loops are places where programmers often make mistakes. Strongly consider doing a careful hand simulation of a loop to see what it does.


Review

It is worth the time to do a quick check to see that a program or part of a program passes a few sanity checks. If it doesn't, it needs to be fixed.

A statement looks like a sentence. It begins on a capitalized word and ends on a period. The program will not work if you forget to capitalize the first word or if you forget the period.