Kat H.

asked • 05/18/21

Row Sums. Write code for the function printRowSums.

Write code for the function printRowSums. It should print the sum of each row of the matrix (put a single space after each sum).

For the matrix shown here:

1 2 3 4 5
6 7 8 9 10


You should print "15 40 "

Hints:

  1. Going to want nested loops...


Code:


#include <iostream>

#include <climits>



using namespace std;


const int NUM_COLS = 5;


void printRowSums(const int values[][NUM_COLS], int numRows) {


//Do not modify anything on or above the line below this

//YOUR_CODE_BELOW


//YOUR_CODE


//YOUR_CODE_ABOVE

//Do not modify anything on or below the line above this



}


int main()

{

int nums[2][NUM_COLS] = {{1, 2, 3, 4, 5},

{11, 2, 3, 4, 5}};


int nums2[5][NUM_COLS] = {{21, 2, 3, 4, 5},

{21, 2, 3, 4, 5},

{1, 12, 3, 4, 5},

{2, 2, 23, 4, 5},

{1, 2, 3, 24, 5}};


printRowSums(nums, 2);

cout << endl;

printRowSums(nums2, 5);

cout << endl;


return 0;

}



Tried Code:


#include <iostream>

#include <climits>



using namespace std;


const int NUM_COLS = 5;


void printRowSums(const int values[][NUM_COLS], int numRows) {


//Do not modify anything on or above the line below this

//YOUR_CODE_BELOW


//YOUR_CODE

long rowTotal=0;


int i,j;




for (i=0; i<numRows; i++)


{


rowTotal = 0;


for (j=0; j<NUM_COLS; j++)


{


rowTotal += values[i][j];


}


cout << rowTotal << " "<< endl;


}




//YOUR_CODE_ABOVE

//Do not modify anything on or below the line above this


}


int main()

{

int nums[2][NUM_COLS] = {{1, 2, 3, 4, 5},

{11, 2, 3, 4, 5}};


int nums2[5][NUM_COLS] = {{21, 2, 3, 4, 5},

{21, 2, 3, 4, 5},

{1, 12, 3, 4, 5},

{2, 2, 23, 4, 5},

{1, 2, 3, 24, 5}};


printRowSums(nums, 2);

cout << endl;

printRowSums(nums2, 5);

cout << endl;


return 0;

}


Results:


OutputExpected
Fail
15
25

35
35
25
36
35


Expected:


15 25
35 35 25 36 35


1 Expert Answer

By:

Patrick B. answered • 05/18/21

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.