I am trying to write a program which prints the number of the largest corner element in 2d array.So far I have written a code, it works with many different imputs, but I'm really stuck with this one and I'm not sure how to fix it.
The code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int n;
int m;
int a[10][10];
int max=0;
cin>>n>>m;
for(int i=0;i<n;i ){
for(int j=0;j<m;j ){
cin>>a[i][j];}
}
int topLeft=a[0][0];
int topRight=a[0][m - 1];
int lowRight=a[n - 1][m - 1];
int lowLeft=a[n - 1][0];
for(int i=0;i<n;i ){
for(int j=0;j<m;j ){
if(topLeft > topRight && topLeft > lowRight && topLeft > lowLeft){
max=topLeft;
}
else if(topRight > topLeft && topRight > lowRight && topRight > lowLeft){
max=topRight;
}
else if(lowRight > topLeft && lowRight > topRight && lowRight > lowLeft){
max=lowRight;
}
else if(lowLeft > topLeft && lowLeft > topRight && lowLeft > lowRight){
max=lowLeft;
}
else if(m<=1){
max=topLeft;
}
else if(n<=1){
max=topRight;
}
}
}
cout<<""<<max<<endl;
return 0;
}
when I input:
3 1
6
8
9
it prints:
"6" instead of "9"
I've tried many different inputs, but I'm stick with this one..
CodePudding user response:
I believe you don't need the whole second part of your code. I mean, assume that being a 2D array
, the angles are always 4
. You just load them into a vector
and find the maximum element
. I hope I have not misunderstood the problem. Below, find the code.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, m;
int a[10][10];
cin >> n >> m;
for(int i=0;i<n;i ){
for(int j=0;j<m;j ){
cin >> a[i][j];
}
}
vector<int> corner = {a[0][0], a[0][m - 1], a[n - 1][m - 1], a[n - 1][0]};
int maxEl = corner[0];
for(unsigned i = 1; i < corner.size(); i )
maxEl = max(maxEl, corner[i]);
cout << "Max: " << maxEl << endl;
return 0;
}