< previous page page_486 next page >

Page 486
Problem-Solving Case Study Monthly Rainfall Averages
0486-01.gif
Problem: Meteorologists have recorded monthly rainfall amounts at several sites throughout a region of the country. You have been asked to write an interactive program that lets the user enter one year's rainfall amounts at a particular site and prints out the average of the 12 values. After the data for a site is processed, the program asks whether the user would like to repeat the process for another recording site. A user response of y means yes and n means no. The program must trap erroneous input data (negative values for rainfall amounts and invalid responses to the Do you wish to continue? prompt).
Input: For each recording site, 12 floating point rainfall amounts. For each Do you wish to continue? prompt, either a y or an n.
Output: For each recording site, the floating point average of the 12 rainfall amounts, displayed to two decimal places.
Discussion: A solution to this problem requires several looping structures. At the topmost level of the design, we need a loop to process the data from all the sites. Each iteration must process one site's data, then ask the user whether to continue with another recording site. The program does not know in advance how many recording sites there are, so the loop cannot be a count-controlled loop. Although we can make any of For, While, or DoWhile work correctly, we'll use a Do-While under the assumption that the user definitely wants to process at least one site's data. Therefore, we can set up the loop so that it processes the data from a recording site and then, at the bottom of the loop, decides whether to iterate again.
Another loop is required to input 12 monthly rainfall amounts and form their sum. Using the summing technique we are familiar with by now, we initialize the sum to zero before starting the loop, and each loop iteration reads another number and adds it to the accumulating sum. A For loop is appropriate for this task, because we know that exactly 12 iterations must occur.
We'll need two more loops to perform data validationone loop to ensure that a rainfall amount is negative and another to verify that the user types only y or n when prompted to continue. As we saw earlier in the chapter, Do-While loops are well suited to this kind of data validation. We want the loop body to execute at least once, reading an input value and test-

 
< previous page page_486 next page >