Index « Previous Next »

Question

Find the sum of each row and each column of matrix of size m x n.

For example for the following matrix output will be like this :

row sum and column sum

Sum of row 1 = 32
Sum of row 2 = 31
Sum of row 3 = 63

Sum of column 1 = 15
Sum of column 2 = 16
Sum of column 3 = 26
Sum of column 4 = 69

Source Code

#include <stdio.h>

int main()
{
    int i, j, m, n;
    int matrix[10][20];
    int sumR, sumC;

    printf("Enter number of rows : ");
    scanf("%d", &m);
    printf("Enter number of columns : ");
    scanf("%d", &n);

    /* Input data in matrix */
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("Enter data in [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }

    printf("\n");

    /* Display the matrix */
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }

    printf("\n");

    /* Find the row-wise sum of matrix */
    for (i = 0; i < m; i++)
    {
        sumR = 0;
        for (j = 0; j < n; j++)
        {
            sumR += matrix[i][j];
        }
        printf("Sum of row %d = %d\n", i + 1, sumR);
    }

    printf("\n");

    /* Find the column-wise sum of matrix */
    for (i = 0; i < n; i++)
    {
        sumC = 0;
        for (j = 0; j < m; j++)
        {
            sumC += matrix[j][i];
        }
        printf("Sum of column %d = %d\n", i + 1, sumC);
    }

    return 0;
}