Chapter 6-3 : The signal trick

 The signal trick 

The problem we need to solve is to find out whether or not an event has occured at the end of a repeat loop. This might be the reading of a particular word, a value...

We're going to use the Signal Trick by using a Boolean variable. Whether this event has occurred or not is shown through a TRUE or FALSE statement.

We start by initializing this variable to a TRUE or FALSE state and in the loop, we're going to set a conditional so that if the event occurs, the state of this Boolean variable is reversed and afterwards can never return to its initial state.

By examining the state of the variable at the end of the repeat loop, we'll know whether the event has occurred or not.

Let's take an example: the program will read some numbers and report whether the value 0 has occurred at least once in the list.

We'll use a Boolean variable called signal. Before the loop, we'll initialize this variable to FALSE, since 0 hasn't yet occurred. In the loop, we'll add a conditional that will set signal to TRUE if the number equals 0.

The program will look like this:

1. Set variable signal to False
2. REPEAT
3.      Display ("Give me a number: ")
4.      Read the number and copy it into the number variable
5.      IF number = 0 THEN
6.           Set signal variable to True
7.      END IF
8. UNTIL number reading is complete
9. IF signal THEN
10.      Display ("0 was in the list of numbers read")
11. ELSE
12.      Display ("0 was NOT in the list of numbers read")
13. END IF

It's important to pay attention to line 9. Usually, in an IF, a UNTIL or a WHILE, we set up a comparison. The result of this comparison will be either TRUE or FALSE, a Boolean element enabling the structure to work. Now, in line 9, we're simply quoting the Boolean variable without performing a comparison, but this works because the very nature of a Boolean variable is to be either TRUE or FALSE. Consequently, simply calling up the contents of this Boolean variable will provide the TRUE or FALSE state directly, and the structure will be able to function.

This point is developed in the Help section of the exercise to be carried out, and you are encouraged read it carefully and understand its scope, as Booleans are important programming tools.

Now put this trick into practice with the bottle rack controller robot exercise.

Good luck!