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

 The trick of the smallest and the largest 

When dealing with values, magnitudes, lengths - all the things that can be compared with each other, it is sometimes necessary to know which is the largest 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 largest. 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 previous smallest value will be replaced by the new smallest value just read. The same applies to the largest 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 largest value if we read only negative numbers.

Let's move ahead to a reliable solution. Simply use the counter trick and, when the first value is read, it will automatically be considered the smallest AND largest 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 largest 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
2. REPEAT
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 largest variable
9.      ELSE
10.           IF number < smallest THEN
11.                Copy number to smallest variable
12.           END IF
13.           IF number > largest THEN
14.                Copy number to largest variable
15.           END IF
16.      END IF
17. UNTIL number reading is complete
18. Display ("The smallest number is "), smallest
19. Display ("The largest number is "), largest

Now complete your task with the game animator robot exercise.

Good luck!