C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Matrix Sum (Row-wise and Column-wise)

C Program: Matrix Sum (Row-wise and Column-wise)

C

#include <stdio.h>

 

int main() {

    int a[10][10];

    int i, j, rows, cols;

    int rowSum, colSum;

 

    // Input number of rows and columns

    printf("Enter number of rows: ");

    scanf("%d", &rows);

    printf("Enter number of columns: ");

    scanf("%d", &cols);

 

    // Input elements of matrix

    printf("\nEnter elements of the matrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    // Display matrix

    printf("\nMatrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            printf("%d\t", a[i][j]);

        }

        printf("\n");

    }

 

    // Calculate Row-wise Sum

    printf("\nRow-wise Sum:\n");

    for (i = 0; i < rows; i++) {

        rowSum = 0;

        for (j = 0; j < cols; j++) {

            rowSum += a[i][j];

        }

        printf("Sum of Row %d = %d\n", i + 1, rowSum);

    }

 

    // Calculate Column-wise Sum

    printf("\nColumn-wise Sum:\n");

    for (j = 0; j < cols; j++) {

        colSum = 0;

        for (i = 0; i < rows; i++) {

            colSum += a[i][j];

        }

        printf("Sum of Column %d = %d\n", j + 1, colSum);

    }

 

    return 0;

}

Output

 
INPUT :
Enter number of rows: 3
Enter number of columns: 3
Enter elements of the matrix:
1 2 3
4 5 6
7 8 9

OUTPUT :
Matrix:
1   2   3
4   5   6
7   8   9

Row-wise Sum:
Sum of Row 1 = 6
Sum of Row 2 = 15
Sum of Row 3 = 24

Column-wise Sum:
Sum of Column 1 = 12
Sum of Column 2 = 15
Sum of Column 3 = 18

Explanation

  1. The program reads a matrix of size rows × cols.
  2. For row-wise sum, it iterates through each row and adds all its elements.
  3. For column-wise sum, it iterates through each column and sums elements vertically.
  4. Results for each row and column are displayed separately.