feco feco - 2 months ago 23
C++ Question

Finding the maximum value of every row in 2D array C++

I've managed to find the minimum value of every row of my 2D array with this

void findLowest(int A[][Cm], int n, int m)
{
int min = A[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (A[i][j] < min)
{
min = A[i][j];
}
}
out << i << " row's lowest value " << min << endl;
}
}


I'am trying to find the maximum value of every row using the same way,but it only shows me first maximum value

void findHighest(int A[][Cm], int n, int m)
{
int max = A[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (A[i][j] > max)
{
max = A[i][j];
}
}
out << i << " row's highest value " << max << endl;
}
}


I can't find what's wrong with the second function and why is it only showing me the first maximum value it finds. Any help ?

Answer

Both functions return the result (maximum or minimum) for the whole array rather than each row, because you set max once rather than once per row. You can get the result for each row as follows:

void findHighest(int A[][Cm], int n, int m)
{
     for (int i = 0; i < n; i++)
     {
         int max = A[i][0];
         for (int j = 1; j < m; j++)
         {
             if (A[i][j] > max)
             {
                max = A[i][j];
             }
         }
         // do something with max
     }
}

or, even better, use the standard library function max_element:

void findHighest(int A[][Cm], int n, int m)
{
     if (m <= 0) return;
     for (int i = 0; i < n; i++)
     {
         int max = *std::max_element(A[i], A[i] + m);
         // do something with max
     }
}

This should give you all values which is easy to check:

#include <algorithm>
#include <iostream>

enum { Cm = 2 };

void findHighest(int A[][Cm], int n, int m) {
  if (m <= 0) return;
  for (int i = 0; i < n; i++) {
    int max = *std::max_element(A[i], A[i] + m);
    std::cout << max << " ";
  }
}

int main() {
  int A[2][2] = {{1, 2}, {3, 4}};
  findHighest(A, 2, 2);
}

prints 2 4.