In: Computer Science
Assume an MxN array has been filled, write a function to calculate the sum of each column which should be stored into a third 1D array of size N. code in C++
#include <iostream>
using namespace std;
#define m 4
#define n 4
// give any value to m and n
void column_sum(int arr[m][n],int arr2[n])
{
int i,j,sum = 0;
int k=0;
cout << "\nFinding Sum of each column:\n\n";
for (i = 0; i < m; ++i) {
for (j = 0; j < n; ++j) {
sum = sum + arr[j][i];
}
arr2[k]=sum;
k++;
cout
<< "Sum of the column "
<< i << " = " << sum
<< endl;
sum = 0;
}
cout<<"The content of 1d array is:\n";
for(i=0;i<n;i++){
cout<< arr2[i] ;
}
}
int main()
{
int i,j;
int arr[m][n];
int arr2[n];
int x = 1;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
arr[i][j] = x++;
column_sum(arr,arr2);
return 0;
}