Link to home
Start Free TrialLog in
Avatar of Computer Guy
Computer Guy

asked on

Add values of each row in an array

Hello,

Not sure where I am going wrong, but I want to display the sum of each row of the array:

#include <iostream>
using namespace std;
int main() {
    int sum = 0;
    int i, j,val[3][4] = {8, 16, 9, 52, //85
                          3, 15, 27, 6, //51
                          14, 25, 2, 10}; //51
    i = 0;
    for (j = 0; j < 4; j++)
        sum = sum+ val[i][j];
    cout << "The value of row 1 is " << sum << endl;
cout << "The value of row 2 is " << sum << endl;
cout << "The value of row 3 is " << sum << endl;

    return 0;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Cong Minh Vo
Cong Minh Vo
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of phoffric
phoffric

#include <iostream>
#include <numeric>

using namespace std;

int main()
{
   int i;
   int val[3][4] = {{8, 16, 9, 52}, //85
		    {3, 15, 27, 6}, //51
		    {14, 25, 2, 10}}; //51

  for (i = 0; i < 3; i++)
  {
     cout << "The value of row "<< i+1<< " is " 
          << accumulate( &val[i][0], &val[i][4], 0) << endl;
  }
}

Open in new window

http://www.cplusplus.com/reference/numeric/accumulate/?kw=accumulate
Avatar of Computer Guy

ASKER

Thank you!