how to write Program to find the sum of each row & column of a matrix of size n x m andif matrix is square, find the sum of the diagonals also.

Join Our Official Freshers Jobs Telegram Channel

Hello friends, Welcome to your Techgsr.co blog. And today in this article we will learn about how to write Program to find the sum of each row & column of a matrix of size n x m andif matrix is square, find the sum of the diagonals also. .So let’s go to our topic

#include <iostream.h>
#include <conio.h>
int main()
{
clrscr();
int A[10][10],m,n,x,y,sum=0;
//Create a Matrix A
cout << “Enter number of rows and columns in Matrix A : \n”;
cin>>n>>m;
cout << “Enter elements of Matrix A : \n”;
for(x=1;x<n+1;++x)
for(y=1;y<m+1;++y)
cin>>A[x][y];
//Find sum of each row
for(x=1;x<n+1;++x)
{
A[x][m+1]=0;
for(y=1;y<m+1;++y)
A[x][m+1]=A[x][m+1]+A[x][y];
}
//Find sum of each column
for(y=1;y<m+1;++y)
{
A[n+1][y]=0;
for(x=1;x<n+1;++x)
A[n+1][y]+=A[x][y];
}cout << “\nMatrix A, Row Sum (Last Column)” << ” and Column Sum (Last Row) : \n”;
for(x=1;x<n+1;++x)
{
for(y=1;y<m+2;++y)
cout << A[x][y] << ”
“;
cout << “\n”;
}
//Print sum of each column
x=n+1;
for(y=1;y<m+1;++y)
cout << A[x][y] << ”
“;
cout << “\n”;
if(m==n)
{
for(x=1;x<m+1;x++)
for(y=1;y<n+1;y++)
if(x==y)
sum+=A[x][y];
else
if(y==m-(x+1))
sum+=A[x][y];
}
cout << “Sum of diagonal elements is : ” << sum << endl;
getch();
return 0;
}

 

This program takes in the number of rows (n) and columns (m) as well as the elements as
a screen input in a matrix n x m.
It then calculates the sum of each row and each column and outputs it using the ‘cout’
command.
Also, if it is a square matrix, it calculates the sum of diagonal elements and prints it out.

INPUT :
3 3
9 8 7 6 5 4 3 2 1
OUTPUT :
Matrix A, Row Sum(Last Column) and Column Sum(Last Row) :
9 8 7 24
6 5 4 15
3 2 1 6
18
15
12
Sum of diagonal elements is : 15

Related Post:-

Predict the output of following C++ program in cpp

Print 1 to 100 in C++, without loop and recursion

Factorial Using Loop Example Program In C++

bfs algorithm in data structure (BFS)

if..else Statement Example Program In C++

For Loop Example Program In C++

Program to find the sum of each row & column of a matrix of size n x m andif matrix is square, find the sum of the diagonals also.

 tudo app using html and css javascript

how to create age calculator in html project

how to make toast in html css and javascript

how to make copy to clipboard in javascript

how to create email validation in javascript

So I hope that you learn about the  Predict the output of following C++ program in cpp And if you have any more queries about computer relegated then feel free to discuss your problem in the comment section.Thank you so much and come back for more updates about Techgsr.co .