Rainfall Averaging

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Using nested loops, calculate the average rainfall across Canada on a given week. This will be done using three arrays. One representing Winnipeg, Vancover, and Halifax. Since we will not be covering arrays for another couple weeks you will need to read ahead to complete this problem. Here are the arrays to use to get you started.

 int winnipeg[] = {10,0,20,4,30,60,0};
int vancover[] = {60,70,100,40,30,50,80};
int halifax[] = {0,0,0,0,0,0,0}; 
 

Getting Started

Wiki loops01.jpg

Solution

To begin this problem we need to state 5 variables. Three integer arrays for the different cities that will be used for our result, the total of all rainfall in each of those cities, and the average of the rainfall. These variables will look something like this.

 int winnipeg[] = {10,0,20,4,30,60,0};       //rainfall amounts in winnipeg sunday to saturday
int vancover[] = {60,70,100,40,30,50,80};   //rainfall amounts in vancover sunday to saturday
int halifax[] = {0,0,0,0,0,0,0};            //rainfall amounts in halifax sunday to saturday

int total = 0;  //total rainfall across country
int avg;        //will hold average rainfall once calculated 

Set up an outer loop to determine which city we will add to the total next. The loop will iterate through 0 to 2, in the example solution Winnipeg was 0, Vancover was 1, and Halifax was 2. An if statement inside the loop will let us determine which one we are adding.

 //winnipeg is 0, vancover is 1, and halifax is 2
for(int i=0;i<3;i++)
{
   if(i == 0)
   { 

Add another loop in each section of the if statement that will loop through the city array to add all data to the total.

 //add all rainfall from winnipeg to total
for(int j=0;j<7;j++)
{
    total += winnipeg[j];
} 

Once we have added all values to the total we can calculate the average. In the example solution I have used the length of the arrays, it is not incorrect to simply divide it by 21 but this is better programming practice.

 //calculate average of all rainfall in canada
avg = total / (winnipeg.length + vancover.length + halifax.length); 

At the end of the program print out the result in any fashion you deem fit.

 //print data
System.out.println("The average rainfall across Canada last week was " + avg + " mm."); 

This is another basic application of nested loops. Once you have done more work with arrays there is a whole world of possibilities you can apply nested loops to.

Code

Solution Code

Back to the Program-A-Day homepage