2D Array

Hi everyone, I'm working on a program that is supposed to collect and analyze collected data for monkeys. The 2D array represents a family of three monkeys(rows) and the columns show the amount of bananas they've eaten for each day of the week. I have the input portion working properly, but the second nested for loop is totaling the data incorrectly. Each time I run the numbers through, it is counting the 1st row data twice. for the life of me I can't see why this is happening, this loop is built the same as the input loop and that one works perfectly. advice anyone?

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

using namespace std;

int main ()
{
	const int NUM_MONK = 3;
	const int NUM_DAYS = 7;
	int food [NUM_MONK][NUM_DAYS];
	int totalfood =0;
	int monk, days; 

	cout <<"This program will calculate the total bananas eaten";
	cout <<"by three monkeys over seven days."<<endl;
	cout <<"Enter the following data: " <<endl;

	//nested loops to fill the array with food data 
	// for each monkey over seven days

	for (monk=0; monk<3;monk++)
	{
		for (days=0; days<7;days++)
		{
			cout <<"Monkey "<<(monk+1);
			cout <<", day "  <<(days+1)<<": ";
			cin>> food[NUM_MONK][NUM_DAYS];

		}
		cout << endl;
	}

	for (monk=0; monk<3;monk++)
	{
		for (days=0; days<7;days++)
		{
			totalfood += food[NUM_MONK][NUM_DAYS];
		}
		cout << endl;
	}

	int avgtotal= (totalfood/7);


	cout <<"Average total bananas to feed monkey family for a day: " <<avgtotal;
	cout <<"Total bananas eaten this week by family: "<<totalfood;

	int x;
	cin >> x;
	return 0;


}
You're not accessing the elements of the array correctly.
Line 28:
 
    cin>> food[NUM_MONK][NUM_DAYS];
should be
 
    cin>> food[monk][days];

and similarly at line 38.

Also note that food[NUM_MONK][NUM_DAYS] is an invalid element, it is outside of the array and thus some other memory will be accessed, with unpredictable (but bad) results.

this loop is built the same as the input loop and that one works perfectly
No, it's far from perfect, it's accessing and corrupting out of bounds memory.
Last edited on
wow i can't believe I was missing that. Thanks for the help!
Topic archived. No new replies allowed.