largest value of 2nd row in 2d array

Hello, my code needs to find largest value of 2nd row in 2d array. Everything works fine untill the column number is 5. What's wrong in the code? for exampe if i enter : 2,5; 1,2,3,4,5; 2,3,1,4,2; it outputs 2 where the answer should be 4.

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
  #include <iostream>
using namespace std;
int main() {
 int n,m,max;
 cin >> n >> m;
 if (n<2){
   cout << "No";
   return 0;
 }
 
 int A[n][m];
 if (m>1){
 for (int i=0; i<n; i++){
  
   for (int j=0; j<m; j++){
      max=A[1][0];
     cin>>A[i][j];
     if (A[1][j]>max) max=A[1][j];
     }
   
   }
 
 cout << max;
 }
 if (m==1){
for (int i=0; i<n; i++){
   for (int j=0; j<m; j++){
     cin>>A[i][j];
     }
   }
   cout << A[1][0];
 }
 
return 0;
}
Last edited on
Your code did not build on my computer because the array needed const values. If we use the values in your example this is what happens.

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
#include <iostream>

using namespace std;
int main() {
	const int n = 2, m = 5; int max;
	//cin >> n >> m;
	if (n<2) {
		cout << "No";
		return 0;
	}

	
	int A[n][m];
	if (m>1) {
		for (int i = 0; i<n; i++) {

			for (int j = 0; j<m; j++) {
				max = A[1][0]; //here max is set to 2 with each loop.
				cin >> A[i][j];
				if (A[1][j]>max) max = A[1][j]; // max changes but the last number entered was 2 so max does not change from 2.
			}

		}

		cout << max;
	}
	if (m == 1) {
		for (int i = 0; i<n; i++) {
			for (int j = 0; j<m; j++) {
				cin >> A[i][j];
			}
		}
		cout << A[1][0];
	}

	cin.ignore();
	cin.get();
	
	return 0;
}
Topic archived. No new replies allowed.