In: Computer Science
(a) Write the function rowSum() that receives a(double type) two-dimensional array using vectors and returns a vector consisting of the sum of elements in each row of the two-dimensional structure. The value of the returned vector at index zero is the sum of the elements in row zero of the two-dimensional structures. At index one of the returned vector is the sum of the elements in row one and so on. (b) Write a main function to test rowSum () function. Create a two-dimensional vector of at least size (5 x 5). Display the array and the content of the returned vector.
#include <bits/stdc++.h>
using namespace std;
vector<double> row_Sum(vector<vector<double>>
vect)
{
//get the size of the vector
int s=vect.size();
//declare a vector
vector<double> rsum;
for(int i=0;i<s;i++)
{
double sum=0;
//calculate sum of each row
for(int j=0;j<s;j++)
{
sum=sum+vect[i][j];
}
//add sum to vector
rsum.push_back(sum);
}
//return the vector which has sum to the rows
return rsum;
}
int main()
{
//declare a 2-D vector
vector<vector<double>> vec;
int n=5;//gave default size as 5
/*//use below if you need other n value
cout<<"Enter the size of array:";
cin>>n;*/
cout<<"Enter the elements of 2-D
vector:"<<endl;
for(int i=0;i<n;i++)
{
vector<double> vecrow;
for(int j=0;j<n;j++)
{
double x;
cin>>x;
//insert the data to each row
vecrow.push_back(x);
}
// push the row vector to 2-d vector
vec.push_back(vecrow);
}
// print the input of 2-d vector
cout<<"The vector contains:\n";
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<vec[i][j]<<" ";
}
cout<<"\n";
}
cout<<"Sum of the rows:\n";
// call the function to get sum of each row as a vector
// pass the 2-d input vector into function
vector<double> res_vec=row_Sum(vec);
//print the sum of each row using vector
for(int i=0;i<res_vec.size();i++)
cout<<res_vec[i]<<" ";
}

comment if any doubts