hello, i hope you doing well all of you . i have a question how can i find the max and the min value of 2d array when i ask the user to put the elements , i tried too hard to find it but it goes under the loop and i need it like sepret i mean after i ask the user to input the elment then i show which one is max and which one is mean. thank you so much cuz you always help me
#include <iostream>
int main()
{
int arr[2][2];
int max = 0;
int min = 0;
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 2; x++)
{
std::cin >> arr[x][y];
}
}
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 2; x++)
{
arr[x][y] > max ? max = arr[x][y] : max = max;
}
}
min = max;
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 2; x++)
{
arr[x][y] < min ? min = arr[x][y] : min = min;
}
}
std::cout << "The max is : " << max << '\n';
std::cout << "The min is : " << min << '\n';
std::cin.ignore();
std::cin.ignore();
return 0;
}
You can combine those for loops into just one but I tried making it easier to understand. =D
I don't think this is 100% correct. If you fill your array with -1, -2, -3, -4 it says that the maximum is 0...
A safer approach would be to start assigning to min and max the value arr[0][0], then check as in thre previous code. The reason is simple: if we say min = max = 0; we are "inventing" a value which could not be in the matrix and lead to error. Instead, if we say min = max = arr[0][0]; we are not inventing anything because we are taking an actual value of the matrix.
#include <iostream>
int main()
{
int arr[2][2];
int max = 0;
int min = 0;
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 2; x++)
{
std::cin >> arr[x][y];
}
}
min = max = arr[0][0];
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 2; x++)
{
if(arr[x][y] > max) max = arr[x][y];
if(arr[x][y] < min) min = arr[x][y];
}
}
std::cout << "The max is : " << max << '\n';
std::cout << "The min is : " << min << '\n';
std::cin.ignore();
std::cin.ignore();
return 0;
}