x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 133

# 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;
}
``````
0
Computer Guy
1 Solution

Commented:
``````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++)
{
sum = 0;
for (j = 0; j < 4; j++)
sum = sum+ val[i][j];
cout << "The value of row "<< i+1<< " is " << sum << endl;
}
``````
0

Commented:
``````#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;
}
}
``````
http://www.cplusplus.com/reference/numeric/accumulate/?kw=accumulate
0

Author Commented:
Thank you!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.