C program to find sum of each row and columns of a matrix

Write a C program to read elements in a matrix and find the sum of elements of each row and columns of matrix. C program to calculate sum of rows and columns of matrix.

Example: If elements of matrix are:
1 2 3
4 5 6
7 8 9
Output:
Sum of row 1 = 6
Sum of row 2 = 15
...
...
Sum of column 3 = 18

Required knowledge:

Basic C programming, For loop, Array, Matrix

Sum of rows and columns of a matrix can be defined as
Rows and columns of a matrix

Program:

/**
 * C program to find sum of elements of rows and columns of matrix
 */

#include <stdio.h>

int main()
{
    int A[3][3];
    int row, col, sum = 0;

    /*
     * Reads elements in matrix from user
     */
    printf("Enter elements in matrix of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /*
     * Finds the sum of elements of each row of matrix
     */
    for(row=0; row<3; row++)
    {
        sum = 0;
        for(col=0; col<3; col++)
        {
            sum += A[row][col];
        }

        printf("Sum of elements of Row %d = %d\n", row+1, sum);
    }
    
    /*
     * Finds the sum of elements of each columns of matrix
     */ 
    for(row=0; row<3; row++)
    {
        sum = 0;
        for(col=0; col<3; col++)
        {
            sum += A[col][row];
        }

        printf("Sum of elements of Column %d = %d\n", row+1, sum);
    }

    return 0;
} 
Output
X
_
Enter elements in matrix of size 3x3:
1 2 3
4 5 6
7 8 9
Sum of elements of Row 1 = 6
Sum of elements of Row 2 = 15
Sum of elements of Row 3 = 24
Sum of elements of Column 1 = 12
Sum of elements of Column 2 = 15
Sum of elements of Column 3 = 18

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment