-2

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?

  • `arr` is a 1D array of type `int[10]`. So when you wrote: `arr[a[i][j]]++`, you're passing `a[i][j]` as index to `arr`'s supscript `operator[]`. This is explained in any [beginner c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Also, see [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jason Sep 14 '22 at 04:42
  • Also, the question might be more suitable for https://math.stackexchange.com/ – Jason Sep 14 '22 at 04:46
  • @JasonLiam yes I am aware of that, but how does it know that elements are being repeated? – user19991342 Sep 14 '22 at 04:52
  • Your assumption that this works seems not entirely correct. For example, suppose(for some other case) `a[i][j]` is greater then `9` then `arr[a[i][j]]` will be undefined behavior. The program is very badly written. – Jason Sep 14 '22 at 05:12
  • Maybe we should try understanding one piece at a time. I'll arbitrarily choose a case... when `i` is `1` and `j` is `2`, what is the value of `a[i][j]`? Which counter should be incremented for this case? – JaMiT Sep 14 '22 at 13:42

1 Answers1

0

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], ...

SebastianWilke
  • 470
  • 1
  • 4
  • 15