0
0
CProgramBeginner · 2 min read

C Program to Add Two Matrices with Output and Explanation

To add two matrices in C, use nested for loops to sum corresponding elements and store them in a result matrix, like result[i][j] = matrix1[i][j] + matrix2[i][j];.
📋

Examples

InputMatrix1: [[1,2],[3,4]] Matrix2: [[5,6],[7,8]]
OutputResultant Matrix: [[6,8],[10,12]]
InputMatrix1: [[0,0],[0,0]] Matrix2: [[0,0],[0,0]]
OutputResultant Matrix: [[0,0],[0,0]]
InputMatrix1: [[-1,2],[3,-4]] Matrix2: [[4,-2],[-3,4]]
OutputResultant Matrix: [[3,0],[0,0]]
🧠

How to Think About It

To add two matrices, think of them as grids of numbers. You add each number in the first matrix to the number in the same position in the second matrix. This means you go row by row and column by column, adding pairs of numbers and saving the sums in a new matrix.
📐

Algorithm

1
Get the number of rows and columns for the matrices.
2
Read the elements of the first matrix.
3
Read the elements of the second matrix.
4
Create a result matrix of the same size.
5
Add corresponding elements from both matrices and store in the result matrix.
6
Print the result matrix.
💻

Code

c
#include <stdio.h>
int main() {
    int rows = 2, cols = 2;
    int matrix1[2][2] = {{1, 2}, {3, 4}};
    int matrix2[2][2] = {{5, 6}, {7, 8}};
    int result[2][2];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }

    printf("Resultant Matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }
    return 0;
}
Output
Resultant Matrix: 6 8 10 12
🔍

Dry Run

Let's trace adding two 2x2 matrices [[1,2],[3,4]] and [[5,6],[7,8]] through the code.

1

Initialize matrices

matrix1 = [[1,2],[3,4]], matrix2 = [[5,6],[7,8]], result = [[0,0],[0,0]]

2

Add element at position (0,0)

result[0][0] = 1 + 5 = 6

3

Add element at position (0,1)

result[0][1] = 2 + 6 = 8

4

Add element at position (1,0)

result[1][0] = 3 + 7 = 10

5

Add element at position (1,1)

result[1][1] = 4 + 8 = 12

6

Print result matrix

Print rows: [6 8] and [10 12]

Positionmatrix1[i][j]matrix2[i][j]result[i][j]
(0,0)156
(0,1)268
(1,0)3710
(1,1)4812
💡

Why This Works

Step 1: Matrix element-wise addition

Each element in the result matrix is the sum of elements from the same position in the two input matrices using result[i][j] = matrix1[i][j] + matrix2[i][j];.

Step 2: Use nested loops

Nested for loops let us visit every row and column index to perform addition systematically.

Step 3: Store and print results

The sums are stored in a new matrix and then printed row by row to show the final added matrix.

🔄

Alternative Approaches

Dynamic input for matrix size and elements
c
#include <stdio.h>
int main() {
    int rows, cols;
    printf("Enter rows and columns: ");
    scanf("%d %d", &rows, &cols);
    int matrix1[rows][cols], matrix2[rows][cols], result[rows][cols];

    printf("Enter elements of first matrix:\n");
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            scanf("%d", &matrix1[i][j]);

    printf("Enter elements of second matrix:\n");
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            scanf("%d", &matrix2[i][j]);

    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            result[i][j] = matrix1[i][j] + matrix2[i][j];

    printf("Resultant Matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            printf("%d ", result[i][j]);
        printf("\n");
    }
    return 0;
}
Allows user to input any size and values, making the program flexible but requires more input handling.
Add matrices in-place modifying first matrix
c
#include <stdio.h>
int main() {
    int matrix1[2][2] = {{1, 2}, {3, 4}};
    int matrix2[2][2] = {{5, 6}, {7, 8}};
    int rows = 2, cols = 2;

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix1[i][j] += matrix2[i][j];
        }
    }

    printf("Resultant Matrix (in-place):\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix1[i][j]);
        }
        printf("\n");
    }
    return 0;
}
Saves memory by updating the first matrix directly but loses original data.

Complexity: O(rows * cols) time, O(rows * cols) space

Time Complexity

The program uses nested loops over rows and columns, so it processes each element once, resulting in O(rows * cols) time.

Space Complexity

It requires extra space for the result matrix of the same size, so space complexity is O(rows * cols). In-place addition can reduce space.

Which Approach is Fastest?

All approaches have similar time complexity; in-place addition saves space but overwrites data, while dynamic input adds flexibility.

ApproachTimeSpaceBest For
Fixed size with separate resultO(rows * cols)O(rows * cols)Simple, clear code
Dynamic input sizeO(rows * cols)O(rows * cols)Flexible matrix sizes
In-place additionO(rows * cols)O(1)Memory efficient, no original data needed
💡
Always ensure both matrices have the same dimensions before adding to avoid errors.
⚠️
Beginners often forget to use nested loops and try to add matrices element-wise without looping through rows and columns.