C PROGRAMMING PROGRAM • MATRICES

Add Two Matrices

Learn how to add two matrices using a clear C program.

Intermediate2D arraysNested loopsMatrices

PROBLEM UNDERSTANDING

Input and expected output

Sample input
2 2
1 2
3 4
5 6
7 8
Sample output
6 8
10 12

COMPLETE C PROGRAM

Complete C implementation

matrix-addition.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int rows, columns, first[10][10], second[10][10];

    scanf("%d %d", &rows, &columns);
    if (rows < 1 || rows > 10 || columns < 1 || columns > 10) return 1;
    for (int row = 0; row < rows; row++)
        for (int column = 0; column < columns; column++) scanf("%d", &first[row][column]);
    for (int row = 0; row < rows; row++)
        for (int column = 0; column < columns; column++) scanf("%d", &second[row][column]);
    for (int row = 0; row < rows; row++) {
        for (int column = 0; column < columns; column++) printf("%d ", first[row][column] + second[row][column]);
        printf("\n");
    }
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

6 8
10 12
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Add elements at identical row and column positions.
  3. Display the computed result.

Add elements at identical row and column positions.

EFFICIENCY

Time and space complexity

Time complexity

O(rows × columns)

Auxiliary space

O(rows × columns)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.