Using Flags


Deciding when to exit a loop using a flag

Sometimes it is awkward to know when to get out of a loop. One way to handle those situations is to create a flag (a variable of type Boolean) that is true to indicate that the loop should keep going and false to indicate that the loop should end.

For example, here is the isPrime(n) function again, this time using a flag to decide whether to keep going. The flag is called keepGoing.

  Define
    isPrime(n: Integer): Boolean by

    isPrime(n) = r |
      Let r = false.
      Let k = 2.
      Let keepGoing = true.
      While keepGoing do
        If k >= n then
          Relet r = true.
          Relet keepGoing = false.
        else
          If n `mod` k == 0 then
            Relet keepGoing = false.
          %If
        %If

        Relet k = k + 1.
      %While
  %Define
As you can see, using a flag often makes a function larger, and can actually work against you by making the program more difficult to understand. But in situations where the decision of whether to keep going is complicated, a flag is an option that can help you manage the decision.


Problems

  1. [solve] Put the isPrime function in a program. Also include a definition of function the nextPrime(n) function from the preceding page. But this time, use a flag to decide whether to keep going. Add some tests of your own to see if nextPrime(n) seems to be working.


Summary

A flag can be a way to decide how to get out of a loop when the decision is awkward to make. So far, we have not seen any really difficult loops, though.


Review

Some loops go through a sequence of values accumulating an answer as they go.

A search loop stops as soon as it encounters what it is looking for.

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

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