Finding Maximum and Minimum Values

A common task that must be done in a loop is to find the maximum and minimum of a sequence of values. The file Temps.java contains a program that reads in a sequence of hourly temperature readings over a 24-hour period. You will be adding code to this program to find the maximum and minimum temperatures. Do the following:

  1. Save the file to your directory, open it and see what's there. Note that a for loop is used since we need a count-controlled loop. Your first task is to add code to find the maximum temperature read in. In general to find the maximum of a sequence of values processed in a loop you need to do two things:

  2. Add code to print out the maximum after the loop. Test your program to make sure it is correct. Be sure to test it on at least three scenarios: the first number read in is the maximum, the last number read in is the maximum, and the maximum occurs somewhere in the middle of the list. For testing purposes you may want to change the HOURS_PER_DAY variable to something smaller than 24 (like 3 or 4) so you don't have to type in so many numbers! You can change the value back to 24 when you have demonstrated to your satisfaction that the program is working properly. Again, if you are having problems, add "trace code"--print statements--inside the loop that show the values of various variables during execution.

  3. Often we want to keep track of more than just the maximum. For example, if we are finding the maximum of a sequence of test grades we might want to know the name of the student with the maximum grade. Suppose for the temperatures we want to keep track of the time (hour) the maximum temperature occurred. To do this we need to save the current value of the hour variable when we update the maxTemp variable. This of course requires a new variable to store the time (hour) that the maximum occurs. Declare timeOfMax (type int) to keep track of the time (hour) the maximum temperature occurred. Modify your if statment so that in addition to updating maxTemp you also save the value of hour in the timeOfMax variable. (WARNING: you are now doing TWO things when the if condition is TRUE.)

  4. Add code to print out the time the maximum temperature occurred along with the maximum. Test your program!

  5. Finally, add code to find the minimum temperature and the time that temperature occurs. The idea is the same as for the maximum. NOTE: Use a separate if when updating the minimum temperature variable (that is, don't add an else clause to the if that is already there). Test your program!