< previous page page_293 next page >

Page 293
Output:
The temperatures (echo print)
The day's high temperature
The day's low temperature
Discussion: This problem is easy to do by hand. We simply scan the list, looking for the highest and lowest values. How do we simulate this process in an algorithm? Well, let's look carefully at what we actually are doing.
To find the largest number in a list of numbers, we compare the first with the second and remember which one is larger. Then we compare that number with the third one, remembering the larger number. We repeat the process until we run out of numbers. The one we remember is the largest. We use the same process to find the smallest number, only we remember the smaller number instead of the larger one.
Now that we understand the process, we can design an algorithm for it:
1. What is the condition that ends the loop? Because there will be exactly 24 values in the list, we can use a counter to control the loop. When it exceeds 24, the loop exits.
2. How should the condition be initialized? The counter should be set to 1.
3. How should the condition be updated? The counter should be incremented at the end of each iteration.
4. What is the process being repeated? The process reads a value, echoprints it, and checks to see if it should replace the current high or low value.
5. How should the process be initialized? In other words, what values should the first number be compared to? We have to give the variables high and low starting values that are to change immediately. So we set high to the smallest number possible (INT_MIN), and wesew low to the greatest number possible (INT_MAX). In this way, the first temperature read is less than low and greater than high and replaces the values in each. (If your C++ system doesn't supply the header file limits.h, in which INT_MIN and INT_MAX are defined, you could use numbers like 30000 and -30000 instead.)
6. How should the process be updated? In each iteration, a new temperature is input and compared with high and low. If it exceeds high, it replaces the old value of high. If it is less than low, it replaces the old value of low. Otherwise, high and low are unchanged. This tells us that the loop contains two If-Then structures, one each for comparing the input value against high and low.
7. What is the state of the program on exiting the loop? Twenty-four temperature values have been input and echo-printed. The loop control variable equals 25, high contains the largest of the input values, and low contains the smallest.

 
< previous page page_293 next page >