Skip to main content

Add two matrices

Short answer

Two matrices of same order are added element-wise: s[i][j] = a[i][j] + b[i][j]. The program reads dimensions and elements, computes sum in nested loops, and displays the sum matrix. Ensure matching rows and columns before addition.

Write a C program to read two matrices from user, add them and display the result in matrix form.

Two matrices can be added only if they have the same order (rows and columns). The sum matrix S has s[i][j] = a[i][j] + b[i][j]. Nested loops read, add and print the matrices.

#include <stdio.h>

int main(void)
{
    int a[10][10], b[10][10], s[10][10], r, c, i, j;
    printf("Enter rows and columns: ");
    scanf("%d %d", &r, &c);
    printf("Enter first matrix:\n");
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &a[i][j]);
    printf("Enter second matrix:\n");
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &b[i][j]);

    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            s[i][j] = a[i][j] + b[i][j];

    printf("Sum of the matrices:\n");
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++)
            printf("%5d", s[i][j]);
        printf("\n");
    }
    return 0;
}

Sample run

Input: 2 3 1 2 3 4 5 6 6 5 4 3 2 1

Enter rows and columns: Enter first matrix:
Enter second matrix:
Sum of the matrices:
    7    7    7
    7    7    7

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →