Home > Software engineering >  find the biggest number in 2D array, except one element
find the biggest number in 2D array, except one element

Time:11-13

I have a task to find the biggest number in 2D array, except the a[2][1] element. The input is:

4
4 2 3 4
8 5 9 6
3 9 8 4
6 4 2 3

The output should be:

9

Im getting the output

8

Since there are two 9's in the array, I dont know how to fix it.


#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
  int n;                           
  int a[10][10];       
  cin>>n;       
  for(int i=0;i<n;i  ){  
    for(int j=0;j<n;j  ){  
      cin>>a[i][j];
    }
}
int max=1;
  for(int i=0;i<n;  i){
        for(int j=0;j<n;  j){
            if(a[i][j]==a[2][1]){
            continue;
            }
            if(a[i][j]>max){
            max=a[i][j];
        }
    }
}

    cout<<max<<endl;  
return 0;
}

Since there are two 9's in the array, I dont know how to skip over the a[2][1] element.

CodePudding user response:

You are ignoring the value of a[2][1] you should ignore the index pair (2,1) instead:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
  int n;                           
  int a[10][10];       
  cin>>n;       
  for(int i=0;i<n;i  ){  
    for(int j=0;j<n;j  ){  
      cin>>a[i][j];
    }
}
int max=1;
  for(int i=0;i<n;  i){
        for(int j=0;j<n;  j){
            if(i == 2 && j == 1){
            continue;
            }
            if(a[i][j]>max){
            max=a[i][j];
        }
    }
}

    cout<<max<<endl;  
return 0;
}
  • Related