Infinite Loop?

The code was working fine until I added in a few arrays. Now an infinite loop occurs if the value of the for loop in the main () function is 12 or higher.

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
  #include <iostream>
#include <string>

using namespace std;

double monthlyrain[11];
int x = 0;

double totalRainfall(double);
double averageRainfall(double, double);


int main()
{
	
	string month[]{ "January ", "February ", "March ", "April ", "May ", "June ", "July ", "August ", "September ", "October ", "November ", "December " };
	
	cout << "Please enter in the total rainfall for each month" << endl;
	
	for (x = 0; x < 12; x++)
	{
		cout << month[x] << endl;
		cin >> monthlyrain[x];
	}
	
	cout << "Annual Rain Report for My County" << endl;
	
	cout << "Total Rainfall: " << totalRainfall( monthlyrain[11] ) << " inches" << endl;
	
	cout << "Average Monthly Rainfall: " << averageRainfall(monthlyrain[11], monthlyrain[11]) << " inches" << endl;


	cin.ignore();
	cin.get();
	return 0;
}
double totalRainfall(double sum) {

	for (x = 0; x < 12; x++)
	{
		sum = monthlyrain[x] + sum;

	}
	
	return sum;
}

double averageRainfall(double sum, double average) {


	for (x = 0; x < 12; x++)
	{
		sum = monthlyrain[x] + sum;
	}
	average = sum / 11;

	return average;
}
You are overwriting monthlyrain when x gets to 11. (line 23).
yeah its because monthlyrain is 11 elements wide and your loop runs 12 times,
and for some reason when you try to write to the twelfth element of monthlyrain x resets
rather than throwing an exception...wired
can someone explain that?
Last edited on
Weird, am I right? Any fixes?
This is A reason to avoid global variables. Take a look at line 7: int x = 0

The x at line 7 is a global variable; therefore, it WILL override your for loop at line 20-23:

1
2
3
4
5
	for (x = 0; x < 12; x++)
	{
		cout << month[x] << endl;
		cin >> monthlyrain[x];
	}


The for loop will loop until the condition x < 12 is met; however, because you have the global variable at line 7, it will start the for loop at 0.

Either, get rid of the global variable or change the counter of the for loop to something like:

1
2
3
4
5
6
    for (int count = 0; count < 12; count++)
    {

	   cout << month[count] << endl;
	   cin >> monthlyrain[count];
    }


Any questions, let us know.

You have other for loops that uses the x as a counter, as well, take a look at them.
Last edited on
Topic archived. No new replies allowed.