understanding on how this program works

I have gotten so frustrated with this exercise i was working on for class and i googled the answer (which i normally hate doing because i like to understand the material but i have a deadline.

The problem was I had to display how many times each number one - nine appeared in a 2d array using a 1d array as a counter.

Now this code works I just want to know how.

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

int main()
{
	//declare numbers array
	int numbers[5][3] = {{1, 2, 7} , {2, 5, 3}, {1, 9, 4}, {2, 6, 5}, {7, 2, 2}};
	int i;
	int count[10]={};

	for(i=0;i<5*3;i++)
		count[numbers[i%5][i/5]]++;

	for(i=0;i<10;i++)
		cout << i << " occurred " << count[i] << " times\n";

	system("pause");
	return 0;
}	//end of main function 
you have count array containing 10 values (indices range [0] - [9]) initialized to 0.
We are passing through 2d array and incrementing value on corresponding index of 1d array
To simplify loop:
1
2
3
4
5
6
7
//He uses following to eliminate nested loops
//http://stackoverflow.com/questions/1730961/convert-a-2d-array-index-into-a-1d-index
for(int i = 0 ;i<5; ++i)
    for(int j =0; j < 3; ++j) {
        int index = numbers[i][j];
        count[index] += 1;
    }

So when it encounters number 5 for example it will increment value in count[5]
Topic archived. No new replies allowed.