In: Computer Science
c++ program to calculate the sum of the rows and the columns in a multidimensional array
#include<iostream>
using namespace std;
int main()
{
int i, j, rows, columns, sum=0;
cout<<"Enter the number of rows : ";
cin>>rows;
cout<<"Enter the number of columns : ";
cin>>columns;
int a[rows][columns],b[rows],c[columns];
for(i=0;i<rows;i++)
{
for(j=0;j<columns;j++)
{
cout<<"Enter the element in row "<<i+1<<" and column "<<j+1<<" : ";
cin>>a[i][j];
}
}
for(i=0;i<rows;i++)
{
sum=0;
for(j=0;j<columns;j++)
{
sum=sum+a[i][j];
}
b[i]=sum;
}
for(i=0; i<rows; i++)
{
sum = 0;
for(j= 0;j<columns; j++)
{
sum = sum + a[j][i];
}
c[i]=sum;
}
sum=0;
for(i=0;i<rows;i++)
{
cout<<"\nThe sum of elements in row "<<i+1<<" : "<<b[i];
sum=sum+b[i];
}
cout<<"\nThe sum of all row in the matrix is : "<<sum<<"\n";
sum=0;
for(i=0;i<columns;i++)
{
cout<<"\nThe sum of elements in column "<<i+1<<" : "<<c[i];
sum=sum+c[i];
}
cout<<"\nThe sum of all columns in the matrix is : "<<sum;
}
The above program will take the input as number of row and number of columns and then it will asks for the user to the elements for each row and colums and then it calculate the sum of every row and store it in the array and then it will calculate the sum of columns and then store hem in an array and then it will print the sum of every row and also the sum of elements of all rows and the then prints the sum of each columns and then also prints the sum of all columns.
SCREENSHOT OF THE OUTPUT :