help

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include<iostream>
using namespace std;

int main()
{
int arr[10][10];
cout<<"Enter please the value of elements\n";
for(int i=0;i<10;i++){
	for(int j=0;j<10;j++){
		cout<<"{"<<i<<"}"<<"{"<<j<<"}";
		cin>>arr[j][i];
	}
}





system("pause");
return 0;


}
You could do something like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#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
Last edited on
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.

So this is how I would do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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;
}
Last edited on
thank you so much for help me with that i appracit it thannnnnk you minomic ,Renthalkx97 . thank you again
Topic archived. No new replies allowed.