Average Rainfall

Pages: 12
I need to write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. It should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate 12 times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period. This is what I have so far and I'm not even sure if it's correct:

#include <iostream>
using namespace std;

int main()
{
int years;

// Get the amount of years.
cout << "Enter how many years of rainfall: ";
cin >> years;

double avgRain = 0;
double rainSum = 0;
int count = 0;
double monthlyTotals[12];
string outRainSum;
string lowMonth;
string highMonth="January";
string monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
cout << "Please enter the amount of rainfall for each month: " << endl;




I have been looking through my textbook and I just can't seem to understand how to put this all together correct.
Last edited on
Seems like you understood first part:
It should first ask for the number of years.

You actually ask howmany years program takes.

Now part 2 you should make for-loop for each year:
1
2
3
for (int i=0; i<years; i++){
// some code here
}


on // some code here -part you need to use some variables such as input, monthTotal, sum and average. Variable sum is used only for average for that period (a year).

Use knowledge (which you have somewhat seems) and try to solve problem with new thing i gave to you; nested loops are actually only 2 or more looping sequences in each other (like 2 for-loops):
1
2
3
4
5
for (int i=0;i<something; i++) {
  for (int j=0; j<something_else; j++) {
    //fancy code here
  }
}
This is my first semester taking a C++ class. the chapter that we are on hasn't introduced anything that you typed. That's why I'm having a hard time understanding it. I've tried looking up examples of something similar to help me with this but everything I look up has stuff that we haven't got to yet. I do better seeing an example of something so that I can look at it and say ok so this code does this. I'm more of a visual learner. Do you think you could come up with a similar program for me to study off of if it's not too much trouble?
Can you tell me which of following keywords you have heard within a class?
-do
-while
-for

None?
step 1: Look through material your teacher gave to you by paper, school website or anything like that.

Can you NOW tell me which of following keywords you just have read from the material?
-do
-while
-for

Like i said earlier: nested loops are actually 2 or more looping sequences within each other. And those looping sequences you might ask? Them are composed via: do, while and for loops.

Show me loop, that you make, which takes 12 numbers (well floats seems from OP) and make average of values given. i'll continue afterwards.



EDIT: Keep original code in another file. Make a new cpp file and show the task above :) Remember: programming is like taking steps while walking: each little step will get you closer to end.
After working loop you actually can make "copy-paste"ing
Last edited on
The section that this assignment comes from in our book is "Count-Controlled Loops: The for Loop." And this is the hint our teacher gave us for this specific assignment: "This is also a count controlled loop and it is nested. The outer loop will respond to user input, the inner loop will iterate twelve times." I actually have to go to work in a few minutes so I will reply again later tonight with the rest of the information you asked for. Thank you for your help!
eraggo wrote:
Now part 2 you should make for-loop for each year:

1
2
for (int i=0; i<years; i++){
// some code here 


H3avenlySoul wrote:
the chapter that we are on hasn't introduced anything that you typed.


H3avenlySoul wrote:
The section that this assignment comes from in our book is "Count-Controlled Loops: The for Loop."


Seems like a case where RTFM is appropriate. The chapter you're on is about the for loop, yet it has no information about the for loop?

Seems like a case where RTFM is appropriate. The chapter you're on is about the for loop, yet it has no information about the for loop?


[offtopic]Sometimes i would LOVE to see thumbs up and thumbs down voting here. :)[/offtopic]
Last edited on
Ok. I have read the chapter and went over that section several times trying to understand it and I don't so that's why I tried to use an alternative solution to find help (this site). If you're just going to say negative things to me, please don't bother commenting. Like I said, this is my first class on C++ and I'm sorry that I'm not comprehending it as well as you. Sorry for wasting your time.
You are not wasting our time at all. You have very good start on original post:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
int years;

// Get the amount of years.
cout << "Enter how many years of rainfall: ";
cin >> years;


double avgRain = 0;
double rainSum = 0;
int count = 0;
double monthlyTotals[12]; // not actually needed
string outRainSum; // sum i was talking earlier :)
string lowMonth; //huh?
string highMonth="January";  //huh?
string monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; // Good: easy to use in INNER loop 


After code above:
1
2
3
4
5
6
7
for (int i=0; i<years; i++) {
  for (int j=0; j<12; j++) { // NOTE: there is 12 months in a year (as you know)
    cout << "This is " << monthNames[j] << ". How much water did sky gave you in this month?";
    //....... More actual code here (you know how: use variable=another_variable+yet_another_variable and so on)
    // cin >> might help you here... Think man; think
  }
}



Lastly: never ever think programming is always taking code other people made for you. There might be bugs (errors in the code you nay not notice).



Simplyfying task helps alot.

Example:
"I need to calculate area of n amount of rectangles" (n will be integer)
Let's think shall we?
-area of rectangle is width*height
->make code to take 2 numbers and multiple those together
-->we have now code snippet that calculates area of ONE rectangle.

Now we have some lines of code which actually do something. That wasn't our task thought.We need way to produce same behavior again and again. That's why we have loops. (in this case for loop):
1
2
3
for (i=0; i<areas_needed_to_be_calculated; i++) {
  //copy-paste earlie code snippet here
}


DONE

p.s. cout helps telling actual results
Ok the i and j is throwing me off. I haven't seen those yet. What do they do?
Ok, some smart person make an outer loop. I feel so tired... :(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    int rainfall[16];
    int data;
    char* month_name[16];
    int total_rain = 0;
    int average_rain = 0;
    int highest_rain = 0;
    int lowest_rain = 0;

    month_name[1] = "January";
    month_name[2] = "February";
    month_name[3] = "March";
    month_name[4] = "April";
    month_name[5] = "May";
    month_name[6] = "June";
    month_name[7] = "July";
    month_name[8] = "August";
    month_name[9] = "September";
    month_name[10] = "October";
    month_name[11] = "November";
    month_name[12] = "December";

    cout << "This program collects rainfall data of 1 year and shows" << endl;
    cout << "the total, avarage, highest, and lowest rainfall." << endl;
    cout << "Enter rainfall in inches." << endl << endl;

    for(int month = 1;month < 13;month++)
    {
        cout << "Enter amount of rainfall for " << month_name[month] << ": ";
        cin >> data;
        total_rain += data;
        rainfall[month] = data;
    }

    average_rain = total_rain / 12;

    cout << endl << "Here is your data set: " << endl << endl;

    for(int relay = 1; relay < 13; relay++)
    {
        cout << "The amount of rainfall for month " << month_name[relay] << " is: " << rainfall[relay] << " inches" << endl;
    }

    int max = 0;
    int min = 9999;
    int max_counter = 0;
    int min_counter = 0;
    int key = 0;

    range:
    for(int relay2 = 1;relay2 < 13;relay2++)
    {
        if(key == 1 && rainfall[relay2] == max)
        {
            max = rainfall[relay2];
            max_counter++;
        }

        if(rainfall[relay2] > max)
        {
            max = rainfall[relay2];
        }
    }

    for(int relay3 = 1;relay3 < 13;relay3++)
    {
        if(key == 1 && rainfall[relay3] == min)
        {
            min = rainfall[relay3];
            min_counter++;
        }

        if(rainfall[relay3] < min)
        {
            min = rainfall[relay3];
        }
    }

    if(key == 0)
    {
        key = 1;
        goto range;
    }


    highest_rain = max;
    lowest_rain = min;

    cout << endl;
    cout << "The total amount of rainfall for the year is: " << total_rain << " inches." << endl;
    cout << "The avarage amount of rainfall for the year is: " << average_rain << " inches." << endl;
    if(max_counter == 1)
    {
        cout << "The highest amount of rainfall was in the month of " << month_name[max] << " with " << highest_rain << " inches." << endl;
    }
    else
    {
        cout << "The highest amount of rainfall was in many months with a record of: " << highest_rain << " inches." << endl;
    }
    if(min_counter == 1)
    {
        cout << "The lowest amount of rainfall was in the month of " << month_name[min] << " with " << lowest_rain << " inches." << endl;
    }
    else
    {
        cout << "The lowest amount of rainfall was in many months with a record of: " << lowest_rain << " inches." << endl;
    }

    system("PAUSE");
    return 0;
}



Oh, couldn't you just run this program many timer?
You all are giving me very in depth programs. I don't think they should be that long. I'm only in the 3rd chapter. Shouldn't they be a little more simple? My past assignments I was able to do in no time. This is just throwing me off because of the whole outer and inner loop thing. That's what I'm not understanding.
Well...This is the only way to go.
@H3avenlySoul: ignore greenleaf800073's program. It's not worth reading because of the way he declared month names array and the GOTO statement.


and I think the program's requirement is
display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.
which means highMonth, lowMonth is not needed.

I guess the output should be
           Jan    Feb    Mar    Apr    May    Jun    Jul    Aug    Sep    Oct    Nov    Dec
Total      xxx    xxx    xxx    xxx    xxx    xxx    xxx    xxx    xxx    xxx    xxx    xxx
Average   xx.x   xx.x   xx.x   xx.x   xx.x   xx.x   xx.x   xx.x   xx.x   xx.x   xx.x   xx.x
@tntxtnt: It wouldn't look like that. The program doesn't need the total and average for each month. The program wants the total months (so how ever many years I put in when it ask me at the beginning multipled by 12), total inches of rainfall (ALL the numbers added together), and the average per month (total amount of rainfall for ALL months divided by (how ever many years I put in when it ask me at the beginning multipled by 12)).

When the program is executed this is how I had it pictured:

How many years: (enter a number)

Enter the amount of rainfall for each month:
Jan: (enter a number for every month)
Feb:
Mar:
Apr:
May:
June:
July:
Aug:
Sep:
Oct:
Nov:
Dec:

Total number of months: (program calculates)
Total inches of rainfall: (program calculates)
Average rainfall per month: (program calculates)
If I had put in 3 when it asked how many years, then Jan would show up 3 times, Feb would show up 3 times, and so on. So I would input a total of 36 numbers for inches of rainfall.
Last edited on
Also, how are you all posting the programs like it looks in the software where each line is numbered?
This is what I have so far. I know a lot needs to be done to the middle and I'm not sure how to calculate total inches at the bottom yet:

#include <iostream>
using namespace std;

int main()
{
int years;

// Get the amount of years.
cout << "Enter how many years of rainfall: ";
cin >> years;

double avgRain = 0;
double rainSum = 0;
int count = 0;
string outRainSum;
string monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
cout << "Please enter the amount of rainfall for each month: " << endl;
for (int i=0; i<years; i++)
{
for (int j=0; j<12; j++)
cout << "Amount of rainfall for " << monthNames[j] << ": ";
cin >> inches;
}

// Calculate the total number of months.
totalMonths = years * 12;

// Display the total number of months.
cout << "Total number of months: " << totalMonths << endl;

// Calculate the total inches of rainfall.
totalInches =

// Display the total inches of rainfall.
cout << "Total inches of rainfall: " << totalInches << endl;

// Calculate the average rainfall per month.
average = totalInches / totalMonths;

// Display the average rainfall per month.
cout << "Average rainfall per month: " << average << endl;

return 0;
}
Also, how are you all posting the programs like it looks in the software where each line is numbered?

wrap around your code with [ code] tags
1
2
3
int main()
{
}

//change [code ] to [code]
[code ]int main()
{
}[/code]

.
how to calculate total inches

change double rainSum = 0; to double totalInches = 0;
1
2
3
4
5
6
7
8
9
10
11
12
for (int i=0; i<years; i++)
{
  for (int j=0; j<12; j++)
  {//you need brackets here
    cout << "Amount of rainfall for " << monthNames[j] << ": ";
   
    cin >> inches;  //get a month rainfall amount
    
    totalInches += inches; //because you don't have an array to store the rainfall amount of each month
                         //so after getting a month rainfall amount, you must add it to totalInches immidiately
  }
}

Pages: 12