2d array row sum

I have 2d array 4x5. How can i find average value of each row, and then print out row numbers in decreasing order of their average values?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "pch.h"
#include <iostream>
using namespace std;

int main() {
	int i, j;
	int arr[4][5] = { 
		{11, 12, 13, 14, 16},
	    {21, 22, 55, 23, 24},
	    {31, 32, 33, 34, 65},
	    {13, 33, 44, 55, 55}
	};

	for (i = 0; i < 4; i++) {
		for (j = 0; j < 5; j++) {
			cout << arr[i][j] << " ";
		}
		cout << "\n";
	}
	
	return 0;
}
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
#include <iostream>
#include <string>
#include <vector>
#include <valarray>
#include <algorithm>
using namespace std;


using ROW = valarray<int>;


void print( const string &title, const vector<ROW> &M )
{
   if ( title != "" ) cout << title << '\n';
   for ( auto &row : M )
   {
      for ( auto e : row ) cout << e << '\t';
      cout << "Average: " << (double)row.sum() / row.size() << '\n';
   }
}


int main()
{
   vector<ROW> M = { { 11, 12, 13, 14, 16 },
                     { 21, 22, 55, 23, 24 },
                     { 31, 32, 33, 34, 65 },
                     { 13, 33, 44, 55, 55 } };
   print( "Before:", M );

   // Sort for DECREASING average
   sort( M.begin(), M.end(), []( ROW a, ROW b ){ return a.sum() > b.sum(); } );
   print( "\nAfter:", M );
}


Before:
11	12	13	14	16	Average: 13.2
21	22	55	23	24	Average: 29
31	32	33	34	65	Average: 39
13	33	44	55	55	Average: 40

After:
13	33	44	55	55	Average: 40
31	32	33	34	65	Average: 39
21	22	55	23	24	Average: 29
11	12	13	14	16	Average: 13.2

Last edited on
Thanks for solving it, but its just too complicated for me, im just begginner, is there any easier way with some basic skills?
Last edited on
White cream, as a beginner it worth looking over the code and work out what it doing..... best way to learn (as I am currently)

In last chances code ignore the print function, that just for nice display output, it nothing that solves the problem.

A Vector is similar to your use of int array (int arr[4][5]) call but a vector offers other functionality such as sort.

In the line
sort( M.begin(), M.end(), []( ROW a, ROW b ){ return a.sum() > b.sum(); } );
he sorts the vector by highest sum in each, if you only have 5 elements in each row sorting by average is same as total value. This the line that sorts the data to how you want.

As a beginner I would advise to look at vectors, you will come across them a lot.

As for the average, for display purposes it is in the print function on the cout statement
cout << "Average: " << (double)row.sum() / row.size() << '\n';
but it is not kept/recorded anywhere.
row.sum taking total of values, row.size number of elements.

Hope that helps a little.

Grun
PS still noob myself so hope you get better answer
Last edited on
Topic archived. No new replies allowed.