C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Matrix addition (2D array)

C Program: Matrix addition (2D array)

C

#include <stdio.h>

 

int main() {

    int a[10][10], b[10][10], sum[10][10];

    int i, j, rows, cols;

 

    // 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 first matrix

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

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

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

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

        }

    }

 

    // Input elements of second matrix

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

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

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

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

        }

    }

 

    // Calculate sum of matrices

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

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

            sum[i][j] = a[i][j] + b[i][j];

        }

    }

 

    // Display the resulting matrix

    printf("\nResultant Matrix (Sum):\n");

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

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

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

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
INPUT :
Enter number of rows: 2
Enter number of columns: 2

Enter elements of first matrix:
1 2
3 4

Enter elements of second matrix:
5 6
7 8


OUTPUT :
Resultant Matrix (Sum):
6   8
10  12


Explanation

  1. The program reads two matrices of equal dimensions.
  2. Each corresponding element is added using nested loops.
  3. The result is stored in a new matrix sum.
  4. The resultant matrix is then printed in matrix form.