Help with my loops

Hi! I'm trying to write a program that gets the number of years someone has data for and then the amount of rainfall for each year, and then total the rainfall amount over the years. My code is...

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
#include <iostream>
using namespace std;

int main()
{
    int rain = 0, data, average, totalRain;

    cout << "\nHow many years have of data do you have to input? ";
    cin >> data;
    cin.ignore();

    for (int n = 1; n <= data; n++)
    {
        cout << "\nWhat is the rainfall amount for year " << n << "? ";
        cin >> rain;
        cin.ignore();

        totalRain += rain;
    }

    average = rain / data;

    cout << "\nThe total number of years is " << data;
    cout << "\nThe total amount of rainfall is " << rain;
    cout << "\nThe average amount of rainfall per year is " << average;
    cin.get();
    return 0;
}


Okay, I think the problem is that every time it loops, it replaces the value of "rain" with whatever number was input. I need it to add all of the values that are input. Say the user inputs 5 for 3 years... the result of rain should be 15, not 5. I also cannot use arrays or additional loops here. Can someone offer some help?
I figured it out... I forgot to initialize my variables like last time.

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
#include <iostream>
using namespace std;

int main()
{
    int rain = 0, totalRain = 0, data, average;

    cout << "\nHow many years have of data do you have to input? ";
    cin >> data;
    cin.ignore();

    for (int n = 1; n <= data; n++)
    {
        cout << "\nWhat is the rainfall amount for year " << n << "? ";
        cin >> rain;
        cin.ignore();

        totalRain += rain;
    }

    average = rain / data;

    cout << "\nThe total number of years is " << data;
    cout << "\nThe total amount of rainfall is " << totalRain;
    cout << "\nThe average amount of rainfall per year is " << average;
    cin.get();
    return 0;
}
Topic archived. No new replies allowed.