How does a 2D array within another array work?

Viewed 35

I am looking at my homework for c++ and having some trouble understanding a part of the code. The code is creating a 2d array and wants to know how many times the elements from 1-9 are repeated.

#include <iostream>
using namespace std;

const int r = 3;
const int c = 4;

void frequency (int a[r][c]);

int main() {
    int elems [r][c] = {{1, 1, 3, 4}, {2, 3, 4, 5}, {6, 9, 9, 9}};

    frequency(elems);

    return 0;
}


void frequency(int  a[r][c]){
    int arr[10] = {};
    for(int i  = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            arr[a[i][j]]++;
        }
    }
    for(int i = 1; i < 10; i++){
        cout << i << " is repeated " << arr[i] <<  " times." << endl;
    }
}

I don't understand how the line arr[a[i][j]]++; works -- how does it act as a counter for elements that are repeated?

1 Answers

I don't understand how the line arr[a[i][j]]++; works -- how does it act as a counter for elements that are repeated?

  • int arr[10] = {}; is creating an int-array with 10 elements (indexed 0-9) all initialized to 0.

  • arr[a[i][j]]++; is (post-)incrementing an element of arr.
    The element at which index? The one at index a[i][j].

You loop through every row in a (i.e. in elems) using i and through every column within that row using j; in essence looping through every element in the order they are spelled in the source code. You are using the numbers in array a to index into the array arr: The first two elements of elems are 1, thus you increment arr[1]. The third number in elems is 3, thus you increment arr[3], ...

Related