Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 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; }
8 Answers
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;
}
+ 2
No, don't set them everytime new in every iteration. You have to initialize BEFORE the loops
+ 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.
+ 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]
+ 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.
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
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;
}
0
ohh thanks alot sir, problem solved. all day i searched for solution. finally solved thank you!!! 😙Matthias Kinshuk Vasisht