Chapter 6-4: The trick of the smallest and the greatest

 The trick of the smallest and the greatest 

When dealing with values, magnitudes, lengths... all things that can be compared with each other, it is sometimes necessary to know which is the greatest and smallest value you have encountered. This is particularly useful in statistics.

Once again, all these values will be read in a repeat loop. The best idea is to define two variables, one that will retain the smallest value and the other that will retain the greatest. Each time a new value is read, it will be compared with the smallest value read up to that point and, if the new value read is smaller, the old smallest value will be replaced by the new smallest value just read. The same applies to the greatest value. It all sounds pretty straightforward once you understand the process.

However, there's a detail to which you need to pay attention: what reference value will you take as the first value? 0? Infinity? We could spend a lot of time showing that any choice carries the risk of having at least one of the two values wrong. For example, if we take 0 as the reference value, the value of the smallest number will be false if we read only positive numbers, and 0 will not represent the greatest value if we read only negative numbers.

Let's move straight on to a reliable solution. Simply use the counter trick and, when the first value is read, it will automatically be considered the smallest AND greatest value, which is the case since there is no other. The first value read will therefore be copied to the variable storing the smallest value, as well as to the variable storing the greatest value. From the second reading onwards, comparisons will begin as explained above.

Here's what the sample program will look like:

1. Initialize counter variable to 0
3.      Display ("Give me a number: ")
4.      Read the number and copy it into the number variable
5.      Add 1 to the contents of the counter variable
6.      IF counter = 1 THEN
7.           Copy number to smallest variable
8.           Copy number to greatest variable
9.      ELSE
10.           IF number < smallest THEN
11.                Copy number to smallest variable
12.           END IF
13.           IF number > greatest THEN
14.                Copy number to greatest variable
15.           END IF
16.      END IF
17. UNTIL number reading is complete
18. Display ("The smallest number is "), smallest
19. Display ("The greatest number is "), greatest

Now complete your task with the game animator robot exercise.

Good work.