Having trouble with two-dimensional arrays.

Apr 10, 2016 at 6:35pm
Hello everyone, I'm required to write a code that displays the amount of time a number appears in a two-dimensional array. Here is what I'm currently working with:


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
 #include <iostream>
using namespace std;

int main()
{
    
    // declare numbers array
    int arrayNumbers[5][3] = {{1, 2, 7} , {2, 5, 3}, {1, 9, 4}, {2, 6, 5}, {7, 2, 2}};
    
    // declare counter array
    int searchFor[9]={1, 2, 3, 4, 5, 6, 7, 8, 9};
   
    int timesOccured = 0;
    int num = 0;
   
    for (int row = 0; row < 5; row++)
        for (int column = 0; column < 3; column++)
            if (arrayNumbers[row][column] == searchFor[num])
            {
                timesOccured++;
                num++;
            }
            else
                num++;

    
      cout << "The amount of " << searchFor[num] << "'s is: " << timesOccured << endl;
}



I'm a bit confused and not exactly sure what I need to fix. I'd love to know what I'm doing wrong.


For reference, the output should be something like:
The amount of 1's is: 2
The amount of 2's is: 5
... and so on.

Thank you for your help.
Apr 10, 2016 at 7:08pm
You'll need to iterate through the arrays and compare them to your searchFor number, which also must be iterated through to change it every time you try a new row of columns. Let me know if you understand what I'm trying to say. I can write it out in code for you, but you won't learn if I do it for you.
Apr 10, 2016 at 8:52pm
I thought I was doing that in the "if" statement. :(
Topic archived. No new replies allowed.