jeudi 13 juillet 2017

Finding the number of occurences of an integer in multidimensional array in C++

I wish to find the number of occurences of a number taken as input in the given multidimensional array defined by the logic below:

...
int a,x,count=0;
cin>> n >> x;
 int a[n][n]  ;
for(int i=1;i<=n;i++)
{
    for(int j=1;j<=n;j++)
    {
        a[i][j]= i*j ;
    }
}
   for( int i=1;i<=n;i++)
{
    for( int j=1;j<=n;j++)

    {
        if(a[i][j] == x)
            ++count;
    }
}
  cout<< count ;
...

For eg., if i give input as 6(n) and 12(to find its number of occurences, 'x' here). The multidimensional array looks something like this:

1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36

Now, the number of occurences of 12 here is 4(count). But when i give n as 10 and x as 5, the program stops working. I can't seem to find what is happening. Can someone help me on this? Also in what way can i modify my code?

Aucun commentaire:

Enregistrer un commentaire