+ 2

How to find the minimum and maximum of a 2d array c++

Hey guys, Where is the problem with my code?? sometimes it doesn't give me the correct answer... #include <iostream> using namespace std; int main() { int A[2][2]; int Min, Max; for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { cin>>A[i][j]; } } for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { cout<<A[i][j]<<" "; if (A[i][j] >= A[0][0]) { Max = A[i][j]; } if (A[i][j] <= A[0][0]) { Min = A[i][j]; } } cout<<endl; } cout<<"Max: "<<Max<<endl; cout<<"Min: "<<Min<<endl; return 0; }

13th Jul 2018, 10:56 AM
AMANULLAH
AMANULLAH - avatar
8 ответов
0
#include <iostream> using namespace std; int main() { int A[2][2]; int Min, Max; for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { cin>>A[i][j]; } } Max = A[0][0]; Min = A[0][0]; for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { cout<<A[i][j]<<" "; if (A[i][j] > Max) { Max = A[i][j]; } if (A[i][j] < Min) { Min = A[i][j]; } } cout<<endl; } cout<<"Max: "<<Max<<endl; cout<<"Min: "<<Min<<endl; return 0; }
13th Jul 2018, 11:34 AM
AMANULLAH
AMANULLAH - avatar
+ 2
No, don't set them everytime new in every iteration. You have to initialize BEFORE the loops
13th Jul 2018, 11:23 AM
Matthias
Matthias - avatar
+ 1
Instead of comparing to A[0][0] everytime, you should initialize Max and Min to A[0][0] and then compare if A[i][j] > Max && A[i][j] < Min.
13th Jul 2018, 11:07 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
You always compare to the first element in your matrix. But you have to compare to the current min or max value. So before the loop set Min = A[0][0] and Max = A[0][0]
13th Jul 2018, 11:07 AM
Matthias
Matthias - avatar
+ 1
As Kinshuk Vasisht has mentioned, you also have to change the if conditions. A[i][j] > Max A[i][j] < Min This is what I meant by "compare to current Min or Max" In order for this to work, you need to initialize Min and Max.
13th Jul 2018, 11:16 AM
Matthias
Matthias - avatar
0
well that wasn't my problem, it works in both case whether i initialize the value before or after. but my question is that sometimes it gives me wrong answer for max and min
13th Jul 2018, 11:12 AM
AMANULLAH
AMANULLAH - avatar
0
Still the same #include <iostream> using namespace std; int main() { int A[2][2]; int Min, Max; for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { cin>>A[i][j]; } } for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { cout<<A[i][j]<<" "; Max = A[0][0]; Min = A[0][0]; if (A[i][j] > Max) { Max = A[i][j]; } if (A[i][j] < Min) { Min = A[i][j]; } } cout<<endl; } cout<<"Max: "<<Max<<endl; cout<<"Min: "<<Min<<endl; return 0; }
13th Jul 2018, 11:19 AM
AMANULLAH
AMANULLAH - avatar
0
ohh thanks alot sir, problem solved. all day i searched for solution. finally solved thank you!!! 😙Matthias Kinshuk Vasisht
13th Jul 2018, 11:33 AM
AMANULLAH
AMANULLAH - avatar