C Program to Find Sum of Each Row in a Matrix

In this example, You learn how to write C program to find sum of each row in a matrix?. We will write a program in C to find sum of rows in a two-dimensional array with example. Here we will read a Matrix in two dimensional array and print the sum of all elements of each row. Let see an example,


#include<stdio.h>
int main()
{   
    int i,j,sum=0,rows,cols;
    printf("Enter Number of rows:");
        scanf("%d",&rows);
    printf("Enter Number of cols:");
        scanf("%d",&cols);
    int a[rows][cols];
    printf("Enter matrix elements:");
    for(i=0;i<rows;i++)
    {
        for(j=0;j<cols;j++)
        scanf("%d",&a[i][j]);
    }
    printf("Matrix elements are:\n");
    for(i=0;i<rows;i++)
    {
        for(j=0;j<cols;j++)
        printf("%d  ",a[i][j]);
        printf("\n");
    }
    for(i=0;i<rows;i++)
    {
        for(j=0;j<cols;j++)
        {
        sum=sum+a[i][j];
        }
    printf("\n Sum of %dth row is %d",i,sum);
    sum=0;
    }
return 0;
}


 Enter Number of rows:2
 Enter Number of cols:2

 Matrix elements are:
 4  6  
 2  4  

 Sum of 0th row is 10
 Sum of 1th row is 6
Happy Coding ๐Ÿ˜Š

No comments:

If you have any doubts, Please let me know

Powered by Blogger.