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
|
Solution
|
Code
Solution Code
public class RainfallAverager {
public static void main(String args[])
{
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
//winnipeg is 0, vancover is 1, and halifax is 2
for(int i=0;i<3;i++)
{
if(i == 0)
{
//add all rainfall from winnipeg to total
for(int j=0;j<7;j++)
{
total += winnipeg[j];
}
}
else if(i == 1)
{
//add all rainfall from vancover to total
for(int j=0;j<7;j++)
{
total += vancover[j];
}
}
else if(i == 2)
{
//add all rainfall from halifax to total
for(int j=0;j<7;j++)
{
total += halifax[j];
}
}
}
//calculate average of all rainfall in canada
avg = total / (winnipeg.length + vancover.length + halifax.length);
//print data
System.out.println("The average rainfall across Canada last week was " + avg + " mm.");
}
}
|
Back to the Program-A-Day homepage