Extracting data from Multidimensional Array

Hey Guys,

Im reading a book and trying to learn code via trial and error using exercises, but I have lots of trouble with iterating through arrays, In my code below, I'm trying to extract data. For example the array below is supposed to be 4 "divisions" of a sales, IE Div A = 59, 44, 21. Div B = 32, 16, 6. so on and so forth.

What I'm trying to achieve is to output the total sales for each Division A, B, C & D. Along with the average of each Division, as I have said I have lots of trouble with for loops/ nested loops so please bear with me i am a noob 8)

1
2
3
4
5
6
7
8
9
10
  #include <iostream>
using namespace std;

int main ()
{
    int sales [][4] = {
    {59, 32, 7, 6},
    {44, 16, 17, 33},
    {21, 6, 9, 56}
 };
I have been practicing with the for loops just seeing what the output is like but have no idea how to extract and calculate certain numbers in the array

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

int main ()
{
    int sales [][4] = {
    {59, 32, 7, 6},
    {44, 16, 17, 33},
    {21, 6, 9, 56}
 };
    for(int row=0; row<3; row++){

        for(int column=0; column<1; column++){
            cout << sales[row][column] << " ";

        }
        cout << endl;
    }

    return 0;
}
Would using a function make this easier perhaps?

I think a commented example might help here.

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

#include <iostream>
using namespace std;

int main()
{

	int total, average;

	int sales[][4] = {

		{ 59, 32, 7, 6 },
		{ 44, 16, 17, 33 },
		{ 21, 6, 9, 56 }

	};

	for (int row = 0; row < 3; row++) {
		// we are at the start of a row, reset the
		// total variable ready.
		total = 0;
		// loop through the values for this row adding
		// each one to the total variable.
		for (int column = 0; column < 4; column++) {
			// add value to total.
			total += sales[row][column];
			// display the value (if you need it)
			cout << sales[row][column] << " ";
		}
		// total holds row total, and we had 4 items so
		// calculate the average.
		average = total / 4;
		// display totals.
		cout << "   - Total: " << total << ", Average: " << average << endl;
	}

	return 0;
}

59 32 7 6    - Total: 104, Average: 26
44 16 17 33    - Total: 110, Average: 27
21 6 9 56    - Total: 92, Average: 23
Last edited on

You may like to check out this good array page: http://www.cplusplus.com/doc/tutorial/arrays/
Topic archived. No new replies allowed.