How to calculate sum of each row in 2d array

closed account (N0M9z8AR)
How can I calculate the sum of each row in an array and put it in a vector?

For example

x1 2 4 4 6 7 Sumx1=??
x2 1 2 3 4 5 etc
x3 1 2 3 4 5
x4 1 2 4 5 6

Here's my attempt
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
  
#include <time.h>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    string name;
    srand(time(NULL));

    int pay[5][4];
    
    for(int i=0; i<5; i++)
    {
        for(int j=0; j<4; j++)
        {
            pay[i][j]=rand()%51+50;
            cout<<pay[i][j]<<"  ";
        }
        cout<<endl;
    }

    cout<<endl<<endl;

    vector<int> totals;

    for(int i=0; i<5; i++){
        for(int c=0; c<4; c++){
            totals.push_back((pay[i][0]+pay[i][1]+pay[i][2]+pay[i][3]));
            }
        cout<<totals[i]<<"  ";
    }

    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
double sum;

for(r = 0; r < numrows; r++)
{
    sum = 0;
    for(c = 0; c < numcols; c++) 
    { 
       sum+= array[r][c];
     }
   vec.push_back(sum);

}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# include <iostream>
# include <vector>
# include <algorithm>
# include <iterator>

constexpr auto ROWS = 4;
constexpr auto COLS = 5;

int main()
{
    int pay[ROWS][COLS] = {{2, 4, 4, 6, 7}, {1, 2, 3, 4, 5} , {1, 2, 3, 4, 5}, {1, 2, 4, 5, 6}};

    std::vector<int> vec{};

    for (auto i = 0; i < ROWS; ++i)
    {
        vec.push_back(std::accumulate(std::begin(pay[i]), std::end(pay[i]), 0));
    }
    for (const auto& elem : vec)std::cout << elem << " ";
}

Couple others: (a) use std::vector<std::vector<int>> as the 2d container (b) use <random> library to generate random numbers
Topic archived. No new replies allowed.