Chapter 6-3 : The signal trick

 The signal trick 

The problem we need to solve is to know, after the end of a repeat loop, whether or not an event has occurred. This could be the reading of a particular word, a value...

We're going to adopt the signal strategy, which we'll be able to implement using a Boolean variable. In effect, the fact that this event has occurred is either TRUE or FALSE.

Consequently, we're going to initialize this variable in a state, TRUE or FALSE 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 can never return to its initial state afterwards.

By examining the state of the variable after 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 would look like this:

1. Set variable signal to False
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 place a comparison. The result of this comparison will be either TRUE or FALSE, a Boolean element for the structure to work. Now, in line 9, we're simply quoting the Boolean variable without performing a comparison, but this will work 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 directly give the TRUE or FALSE state, and the structure will be able to function.

This point is developed in the help section of the exercise to be carried out, so you'd better read it carefully and understand its scope, as Booleans are exceptional programming tools.

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

Have a good work