Write a C program to add two matrices

Description: Take the elements of two 2 x 2 matrices as input. Print the sum matrix.

Hint:

  • Add the elements which are at the same row and column: sum[i][j] = a[i][j] + b[i][j].

C program to add two matrices

#include <stdio.h>

int main(void) {
    int a[2][2], b[2][2], sum[2][2];

    printf("Enter 4 elements of the first matrix: ");
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            scanf("%d", &a[i][j]);

    printf("Enter 4 elements of the second matrix: ");
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            scanf("%d", &b[i][j]);

    printf("Sum of the matrices:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            sum[i][j] = a[i][j] + b[i][j];
            printf("%d ", sum[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Output:

Output of the above program is

Enter 4 elements of the first matrix: 1
2
3
4
Enter 4 elements of the second matrix: 5
6
7
8
Sum of the matrices:
6 8
10 12

How it works

  • The nested loops go through each row and each column.
  • The result matrix has two rows: 6 8 and 10 12.

Read C Two Dimensional Arrays.


Learn more about the similar topics:
Tutorials
C Arrays
C Two Dimensional Arrays
C Passing Arrays to Functions
C Strings
C String Input and Output
C String Functions
C strlen() Function
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?