Photo by Ant Rozetsky on Unsplash
C program to input a matrix from the user and find the row sum and the column sum.
This program inputs a matrix from the user and then uses the "i" and "j" value from the for loop to choose the element from the matrix and add them.
for(int i=0;i<m;i++)
{
int csum=0;
for(int j=0;j<n;j++)
{
csum=csum+arr[j][i];
}
printf("\nSum of all the elements in column %d is %d\n",i,csum);
}
In this part of the code lets take an example of 2*2 matrix. When j=1,and becomes j=2, i value remains 1. Hence the columns get added up. The same thing happens in rows when we take arr[i][j]. The i value is 1. and the j value keeps on changing hence the rows get added up.
#include <stdio.h>
int main()
{
int m,n; //Row Column Declaration
printf("Enter the number of rows and column\n");
scanf("%d %d",&m,&n); //Row Column Initialization
int arr[m][n]; //Matrix Declaration
printf("Enter the elements of the matrix\n");
for(int i=0;i<m;i++) //Matrix Initialization
{
for(int j=0;j<n;j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("\nElements in the matrix are \n"); for(int i=0;i<m;i++) //Print Matrix
{
for(int j=0;j<n;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
printf("\nRow Sum. .. \n");
for(int i=0;i<m;i++)
{
int rsum=0;
for(int j=0;j<n;j++)
{
rsum=rsum+arr[i][j];
}
printf("\nSum of all the elements in row %d is %d\n",i,rsum);
}
printf("\nColumn Sum. .. \n");
for(int i=0;i<m;i++)
{
int csum=0;
for(int j=0;j<n;j++)
{
csum=csum+arr[j][i];
}
printf("\nSum of all the elements in column %d is %d\n",i,csum);
}
return 0;
}
Hope you learnt something because of this blog. Dont forget to follow.
Thankyou...