Biggest number in every row in 2 dimensional array c++

Hey guys can someone help me.. I have exercise which says: in 2 dimensional array find the biggest number in every row and print it.. I find this code but i don't know if it's okey...Please help!

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
45
46
#include<bits/stdc++.h> 
using namespace std; 
const int N = 4;  
  
  
    // Print array element 
    void printArray(int result[], int no_of_rows) { 
        for (int i = 0; i < no_of_rows; i++) { 
            cout<< result[i]<<"\n"; 
        } 
  
    } 
  
    // Function to get max element 
    void maxelement(int no_of_rows, int arr[][N]) { 
        int i = 0; 
          
        // Initialize max to 0 at beginning 
        // of finding max element of each row 
        int max = 0; 
        int result[no_of_rows]; 
        while (i < no_of_rows) { 
            for (int j = 0; j < N; j++) { 
                if (arr[i][j] > max) { 
                    max = arr[i][j]; 
                } 
            } 
            result[i] = max; 
            max = 0; 
            i++; 
  
        } 
        printArray(result,no_of_rows); 
  
    } 
  
    // Driver code 
    int main() 
    { 
        int arr[][N] = { {3, 4, 1, 8}, 
                        {1, 4, 9, 11}, 
                        {76, 34, 21, 1}, 
                        {2, 1, 4, 5} }; 
    // Calling the function  
        maxelement(4, arr); 
    } 
1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
#include<valarray> 
using namespace std; 

int main() 
{ 
   valarray< valarray<int> > A = { { 3,  4,  1,  8 }, 
                                   { 1,  4,  9, 11 }, 
                                   {76, 34, 21,  1 }, 
                                   { 2,  1,  4,   5} }; 
   for ( auto &row : A ) cout << row.max() << '\n';
}

8
11
76
5




Or just:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<algorithm>
using namespace std; 

int main() 
{
   const int N = 4;
   int A[N][N] = { { 3,  4,  1,  8 }, 
                   { 1,  4,  9, 11 }, 
                   {76, 34, 21,  1 }, 
                   { 2,  1,  4,  5 } }; 
   for ( auto &row : A ) cout << *max_element( row, row + N ) << '\n';
}
Last edited on
21:30: warning: ISO C++ forbids variable length array 'result' [-Wvla]

Line 21 is not valid C++.
The compiler should generate instructions to allocate an array there, but the compiler cannot know for how large array, for the no_of_rows could be decided by the user years after compilation.

The array is not required in this task. The logic could be:
for each row in 2D array
  get max of row
  print max
Registered users can post here. Sign in or register to post.