Placement Prep

Program to Add Two Matrices in C, Java, and Python

How to add two matrices in C, Java, and Python: algorithm, worked example, O(m×n) time and space complexity, and common placement coding test mistakes.

By FACE Prep Team 6 min read
matrix-addition c-programming java python data-structures placement-prep time-complexity

Matrix addition has one rule that decides whether the operation is possible: both matrices must have the same number of rows and the same number of columns.

When Matrix Addition Is Valid

Matrix addition is defined element by element. For two matrices A and B, the sum C = A + B is computed as:

C[i][j] = A[i][j] + B[i][j] for every row i and every column j.

This is only meaningful when A and B have matching dimensions. A 2×3 matrix added to a 3×2 matrix is undefined. The element counts match (6 each), but the positions don’t.

Consider a concrete pair:

Matrix A (2×3):

Col 0Col 1Col 2
Row 0123
Row 1456

Matrix B (2×3):

Col 0Col 1Col 2
Row 0789
Row 1123

Result C = A + B (2×3):

Col 0Col 1Col 2
Row 081012
Row 1579

Each cell of C is the sum of the corresponding cells from A and B. No element from one row contributes to another row; that is what makes addition structurally different from multiplication.

The dimension check is not optional. Write it before the nested loop in any placement submission. An interviewer who sees code that skips the check will note it.

Algorithm for Matrix Addition

The algorithm is a direct implementation of the element-wise rule:

  • Step 1: Read the number of rows m and columns n.
  • Step 2: Check that A and B have the same dimensions. If they differ, report an error and stop.
  • Step 3: For i = 0 to m-1:
    • For j = 0 to n-1:
      • Set C[i][j] = A[i][j] + B[i][j].
  • Step 4: Print matrix C.

Two nested loops, one operation per cell. The outer loop iterates over rows; the inner loop iterates over columns. The order (row-major) matches how C, Java, and Python lay out 2D arrays in memory, so this is also the cache-efficient traversal.

The result array C must be declared before entering the nested loop. Declaring it inside the inner loop allocates a new array on every iteration and writes only the current cell; every other cell is uninitialised or zeroed, depending on the language. This is the most common placement coding error for this problem.

Program to Add Two Matrices in C

#include <stdio.h>
#define MAX 10

int main() {
    int a[MAX][MAX], b[MAX][MAX], c[MAX][MAX];
    int m, n, i, j;

    printf("Enter rows and columns: ");
    scanf("%d %d", &m, &n);

    printf("Enter matrix A (%d x %d):\n", m, n);
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);

    printf("Enter matrix B (%d x %d):\n", m, n);
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &b[i][j]);

    /* Matrix addition */
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            c[i][j] = a[i][j] + b[i][j];

    printf("Result C = A + B:\n");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++)
            printf("%d ", c[i][j]);
        printf("\n");
    }
    return 0;
}

Three things to note in the C implementation:

  • MAX 10 bounds the array to 10×10. For placement tests, 10×10 covers every standard test case. Dynamic allocation with malloc is valid but adds pointer-management complexity that the test rarely requires.
  • The result array c is declared at the top of main, not inside the loop. This is the correct pattern.
  • scanf reads into a[i][j] directly. No intermediate variable needed.

For the 2×3 input from the worked example above, the output would be:

8 10 12
5 7 9

Program to Add Two Matrices in Java and Python

Java

import java.util.Scanner;

public class MatrixAddition {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter rows and columns: ");
        int m = sc.nextInt(), n = sc.nextInt();

        int[][] a = new int[m][n];
        int[][] b = new int[m][n];
        int[][] c = new int[m][n];

        System.out.println("Enter matrix A:");
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                a[i][j] = sc.nextInt();

        System.out.println("Enter matrix B:");
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                b[i][j] = sc.nextInt();

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                c[i][j] = a[i][j] + b[i][j];

        System.out.println("Result C = A + B:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++)
                System.out.print(c[i][j] + " ");
            System.out.println();
        }
    }
}

Java allocates int[m][n] at runtime, so no MAX constant is needed. The logic is otherwise identical to the C version: same loop structure, same addition.

Python

def add_matrices(A, B):
    rows = len(A)
    cols = len(A[0])
    C = [[A[i][j] + B[i][j] for j in range(cols)] for i in range(rows)]
    return C

m, n = map(int, input("Enter rows and columns: ").split())
A = [list(map(int, input().split())) for _ in range(m)]
B = [list(map(int, input().split())) for _ in range(m)]

if len(A) != len(B) or len(A[0]) != len(B[0]):
    print("Dimension mismatch: cannot add matrices.")
else:
    C = add_matrices(A, B)
    for row in C:
        print(*row)

The Python version uses a list comprehension for the addition, which is idiomatic but functionally identical to the nested-loop approach. Note that len(A) gives row count and len(A[0]) gives column count, both required for the dimension check.

For placement compilers that use Python 2, replace input() with raw_input(). Most modern online judges use Python 3.

Time Complexity, Space Complexity, and What Placement Tests Expect

Time Complexity

The addition loop visits every cell of the m×n result matrix exactly once. Each visit does a constant-time read from A and B plus one addition. Total work: m×n additions. Time complexity is O(m×n).

The Big-O Cheat Sheet classifies this as O(n²) for the square-matrix special case where m = n = N, which is the notation placement MCQs most commonly use. Both are correct; the m×n form is more general.

Space Complexity

Three matrices are in memory simultaneously: A, B, and C, each of size m×n. Total memory is 3 × m × n integers. Since the input matrices A and B are part of the problem’s input, the auxiliary space (extra space the algorithm allocates beyond input) is the result matrix C alone: O(m×n).

See space complexity of algorithms for how placement tests phrase this distinction between total space and auxiliary space. It matters when the examiner asks “space complexity of the algorithm” vs. “total memory used.”

Common Placement Test Pitfalls

  • Loop bound errors: using i <= m instead of i < m reads one row past the array. The program may not crash on small inputs but will on larger ones.
  • Wrong complexity answer: writing O(n) for matrix addition is a common MCQ trap. The correct answer for an m×n matrix is O(m×n), or O(n²) when m = n.
  • Forgetting the dimension check: a question that asks “what happens when dimensions mismatch” is checking whether you coded the guard condition.
  • Declaring the result array inside the loop: this is a logic error, not a syntax error, so the compiler won’t catch it.

Problems like finding all symmetric pairs in an array test the same nested-loop pattern in a different context; working through both helps reinforce the off-by-one discipline. Similarly, the equilibrium index of an array is another placement classic that rewards careful index tracking.

Why Matrix Operations Matter Beyond the Placement Round

The O(m×n) iteration that makes matrix addition predictable is also the foundation of every neural network’s forward pass. A single layer multiplies an input matrix by a weight matrix and adds a bias matrix (element-wise) across millions of float values. NumPy, PyTorch, and TensorFlow all implement this at GPU scale using the same two-nested-loop logic, vectorised in C or CUDA.

Understanding matrix addition at the algorithm level (not just calling A + B) is what lets you read the PyTorch source or the NumPy documentation and follow what is happening. If you want to go from this nested-loop understanding to building and deploying actual AI models, TinkerLLM starts at ₹299 and covers the Python ML stack from NumPy matrix operations to production LLM deployments.

Primary sources

Frequently asked questions

Can you add two matrices of different sizes?

No. Matrix addition requires both matrices to have exactly the same number of rows and the same number of columns. A 2×3 matrix and a 3×2 matrix cannot be added even though they have the same total element count.

What is the time complexity of adding two matrices?

O(m×n) where m is the number of rows and n is the number of columns. The algorithm visits each of the m×n cells exactly once to perform a single addition, so the total work scales linearly with the size of the matrix.

How does NumPy handle matrix addition in Python?

NumPy allows direct addition with the + operator: C = A + B, where A and B are NumPy arrays. NumPy checks dimensions automatically and raises a ValueError if they do not match. Under the hood it still performs element-wise addition, but the computation is vectorised in C for speed.

What is the difference between matrix addition and matrix multiplication?

Matrix addition is element-wise: C[i][j] = A[i][j] + B[i][j], and requires identical dimensions. Matrix multiplication multiplies rows by columns and is valid whenever the number of columns in the first matrix equals the number of rows in the second. Time complexity for addition is O(m×n); for standard multiplication it is O(m×n×p).

Why do placement tests use small matrices like 3×3 or 4×4?

Small matrices keep input entry manageable in a timed test and are large enough to reveal off-by-one errors in loop bounds. The logic that works for a 3×3 matrix generalises to any m×n matrix; the test is checking that your loops use the correct bounds, not your speed.

Does adding two matrices modify the original matrices?

No. The standard implementation writes each sum into a separate result array C. Arrays A and B are read-only in the addition loop. If you write the sum back into A[i][j], you overwrite the original data, which is a common placement bug to avoid.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF