Perform Matrix Subtraction in C

Beginner
⏱️ 11 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
2D arrays

What You’ll Learn

Matrix subtraction is the entry-by-entry difference of two matrices of identical shape: Cij = Aij − Bij. This tutorial covers the shape rule, nested loops, negatives in the result, a live preview, worked C examples (3×3 and 2×2), edge cases, and O(m·n) complexity.

Definition

Cij = Aij − Bij

Subtract corresponding entries when shapes match.

Same Shape

m × n

Identical rows and columns — same rule as addition.

Nested Loops

i, then j

One subtraction per cell; no shared k dimension.

Negatives OK

int signs

When B exceeds A in a cell, the difference is negative.

Live Preview

3×3 A−B

See both factors and the difference instantly.

Not Multiply

≠ AB

Unlike multiplication, order of cells is entrywise only.

Introduction

For matrices A and B of the same shape, matrix subtraction produces C = A − B where Cij = Aij − Bij for every row i and column j.

Equivalently, subtracting B is adding (−B) entrywise. In C interviews you write the same double nest as addition, swap + for -, and expect negatives.

Why it matters?

It locks in the element-wise pattern after addition and before transpose — and quizzes whether you know order matters (A − BB − A).

Key Highlights

Cell Minus Cell

Same indices in A and B.

Match Shape

Same rows and columns required.

Order Matters

B − A = −(A − B).

O(m·n)

One pass over every entry.

In short: for each i,j set C[i][j] = A[i][j] - B[i][j] — same loops as addition, different operator.

📝 Problem & Approach

Given two matrices of the same size, compute C = A − B entrywise and print the factors plus the difference.

c
/* A and B both 3×3 → C 3×3
 * C[0][0] = 5 - 3 = 2
 * C[0][2] = 2 - 7 = -5   (negatives are normal)
 */

Inputs & Outputs

ItemTypeDescription
mat1, mat22D arraysOperands; must share the same dimensions.
result2D arrayDifference; each cell is one subtraction.
ROWS / COLSmacrosShape for the generalized 2×2 sample.

Minimal workflow

Pseudocode
function subtract_matrices(A, B, C, rows, cols):
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            C[i][j] ← A[i][j] − B[i][j]

Method comparison

OperationRuleLoops
Subtraction (this page)Aij − BijDouble nest; same shape
AdditionAij + BijDouble nest; same shape
Matrix multiplyRow·column sumsTriple nest; inner sizes match

⚡ Quick Reference

GoalPattern
One cellresult[i][j] = a[i][j] - b[i][j];
Compatibilityrows(A) == rows(B) and cols(A) == cols(B)
RelationA - B = A + (-B) entrywise
ReverseB - A = -(A - B)
CostO(m · n) for m × n

📋 Subtract vs Add vs Multiply

Related matrix operations — only subtraction and addition share the same double-loop shape rule.

A − B
Aij-Bij

This page — element-wise

Addition
Aij+Bij

Same loops; swap the operator

Multiply
Σ Aik Bkj

Different rules; triple nest

Interview tip
order!

A−B ≠ B−A in general

Context

When This Problem Shows Up

Reach for matrix subtraction when comparing grids cell by cell or forming residuals.

  1. Interview warm-up

    Same structure as addition; tests negatives and order.

  2. Error / residual grids

    Difference between predicted and actual tables.

  3. Image / pixel deltas

    Conceptual cousin: subtract corresponding samples.

  4. Contrast with multiply

    Clarify element-wise vs row·column products.

  5. Not for mismatched shapes

    Refuse when dimensions differ.

Key benefit: one clear element-wise pattern that proves you understand shape rules and signed results.

🔮 Live Preview

Uses the same 3×3 integer matrices as Example 1. Press the button to print Matrix 1, Matrix 2, and Matrix1 − Matrix2.

Matches the sample matrices in code Example 1.

Live result
Press “Show 3×3 difference”.

Examples Gallery

Two complete C programs — a classic 3×3 difference (with negatives) and a smaller 2×2 you can check by hand. Click View Output to reveal sample console results.

📚 Getting Started

Double nest: one subtraction per matching cell.

Example 1 — Subtract Two 3×3 Matrices

subtract_matrices computes matrix1 − matrix2. Differences can be negative — that is expected.

c
#include <stdio.h>

void subtract_matrices(int mat1[3][3], int mat2[3][3], int result[3][3]) {
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            result[i][j] = mat1[i][j] - mat2[i][j];
        }
    }
}

void display_matrix(int matrix[3][3]) {
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    int matrix1[3][3] = {
        {5, 8, 2},
        {7, 4, 9},
        {3, 6, 1}
    };
    int matrix2[3][3] = {
        {3, 1, 7},
        {6, 9, 2},
        {8, 5, 4}
    };
    int result_matrix[3][3];

    subtract_matrices(matrix1, matrix2, result_matrix);

    printf("Matrix 1:\n");
    display_matrix(matrix1);

    printf("\nMatrix 2:\n");
    display_matrix(matrix2);

    printf("\nResultant Matrix (Matrix1 - Matrix2):\n");
    display_matrix(result_matrix);

    return 0;
}

How It Works

Each result[i][j] is one subtraction. Tab spacing keeps columns readable in the terminal. Notice cells like 2 - 7 = -5 — signed int handles this naturally.

📈 Practical Patterns

Same pattern with macros for rows and columns.

Example 2 — Subtract Two 2×2 Matrices

Useful when an interviewer asks for a smaller trace-by-hand example. Here 1 - 4 = -3 and 4 - 1 = 3.

c
#include <stdio.h>

#define ROWS 2
#define COLS 2

void subtract_matrices(int a[ROWS][COLS], int b[ROWS][COLS], int out[ROWS][COLS]) {
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            out[i][j] = a[i][j] - b[i][j];
        }
    }
}

void print_matrix(const char *title, int m[ROWS][COLS]) {
    printf("%s\n", title);
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            printf("%d ", m[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    int a[ROWS][COLS] = {
        {1, 2},
        {3, 4}
    };
    int b[ROWS][COLS] = {
        {4, 3},
        {2, 1}
    };
    int c[ROWS][COLS];

    subtract_matrices(a, b, c);

    print_matrix("A", a);
    printf("\n");
    print_matrix("B", b);
    printf("\n");
    print_matrix("A - B", c);

    return 0;
}

How It Works

ROWS / COLS make the shape easy to change. Negatives and positives appear together in one small grid.

🧠 How the Algorithm Subtracts Matrices

1

Check same shape

Confirm A and B share row and column counts.

Shape
2

Subtract per cell

Nested loops over i and j; assign A[i][j] - B[i][j].

Diff
3

Print

Optional helper to print each row on its own line.

Display
=

Difference ready

For the 3×3 sample, top-left is 2; negatives like -5 appear where B wins.

🔎 Worked Walkthrough — First Row of the 3×3 Sample

Trace row 0 of Matrix1 − Matrix2.

jA[0][j]B[0][j]A − B
0532
1817
227-5

So the first result row is 2   7   -5. Repeat the same pattern for every other row.

Use Cases

Where matrix-subtraction thinking shows up beyond the interview prompt.

1. Nested-Loop Practice

Master 2D indexing with a simple operator.

Example: i, then j.

2. Residual Tables

Compare expected vs actual entrywise.

Example: score or sensor grids.

3. Signed Results

Prove you handle negatives without panic.

Example: 3×3 sample output.

4. Pair with Addition

Show A − B = A + (−B) on the whiteboard.

Example: interview follow-up.

5. Non-Commutativity

Swap operands and show opposite signs.

Example: B − A = −(A − B).

6. Overflow Awareness

Huge magnitudes can still overflow int.

Example: suggest long long when needed.

Pro Tip: say “same shape, then cell minus cell” before writing the loops — and mention negatives up front.

Advantages

Why this approach earns interview points.

  1. 1. Mirrors Addition

    Reuse the same structure; only the operator changes.

  2. 2. Easy to Generalize

    Macros or parameters for rows and columns scale cleanly.

  3. 3. Clear Complexity

    O(m·n) is the expected answer.

  4. 4. Hand-Checkable

    2×2 and one row of 3×3 dry-run cleanly on a whiteboard.

Pro Tip: avoid unsigned when the result can be negative — mention that if the interviewer probes types.

Usage Tips

Small habits that keep matrix-subtraction code clean in interviews.

  1. 1. Confirm Shape First

    Say both matrices are m × n before coding.

  2. 2. Keep Operand Order Clear

    Write A - B, not a swapped expression by accident.

  3. 3. Expect Negatives

    Use signed types; dry-run one cell that goes negative.

  4. 4. Relate to Addition

    Mention A - B = A + (-B) if asked for theory.

  5. 5. In-Place Only When Safe

    Overwrite an operand only if you no longer need the original.

Pro Tip: the first-row walkthrough table is the fastest way to lock in negatives before typing the full nest.

Common Pitfalls

Mistakes that commonly break matrix-subtraction solutions in C.

  1. 1. Mismatched Dimensions

    Subtracting differently sized matrices is undefined.

    → Require identical m and n.

  2. 2. Swapping Operands

    Writing B - A when the prompt wants A - B.

    → Keep left and right factors in the stated order.

  3. 3. Using Unsigned Types

    Negatives wrap around and look like huge positives.

    → Prefer signed int (or wider) when differences can be negative.

  4. 4. Confusing with Multiplication

    Adding a k loop is wrong for subtraction.

    → Stay with double nest and matching indices.

  5. 5. Ignoring Overflow

    Extreme magnitudes can still overflow signed int.

    → Mention wider types for large inputs.

Edge Cases

Most issues match matrix addition: wrong sizes or numeric range — plus signed results.

Shape

Mismatched matrices

Subtraction needs identical dimensions, same as addition.

Signs

Negative entries

When B exceeds A in a cell, the difference is negative — that is correct.

Order

A − B vs B − A

Not commutative; reverse is the entrywise negation.

Range

int overflow

Very large magnitudes can overflow; consider wider integer types.

Types

Unsigned traps

Avoid unsigned if negatives are possible.

Zero

A − A

Subtracting a matrix from itself yields the zero matrix — good sanity check.

🔄 Input / Output

Programs above embed matrices in source. Interactive versions would read values with scanf after checking dimensions.

SampleResult highlight
3×3 demoFirst row of A−B is 2   7   -5
2×2 demoA−B = [[-3, -1], [1, 3]]

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Trace row 1 by hand

  • Use the 3×3 sample factors
  • Confirm middle row is 1   -5   7

2. Compute B − A

  • Swap operands for the 2×2 sample
  • Show it is the negation of A − B

3. Generalize size

  • Change ROWS/COLS to 4×3
  • Keep the same double nest

4. Zero check

  • Subtract a matrix from itself
  • Verify the zero matrix

Notes

  • Definition: C = A − B with Cij = Aij − Bij; same shape required.
  • Nested loops; each cell is one subtraction.
  • Relation: A − B = A + (−B) entrywise.
  • Negatives are normal when B exceeds A in a cell.

Quick Takeaway: match shapes, then for each cell compute A[i][j] - B[i][j] — same loops as addition, watch the order and the signs.

⏱️ Time and Space Complexity

OperationTimeExtra space
Subtract two m × n matricesO(m · n)O(1) besides result storage
Wrap Up

🎉 Conclusion

Matrix subtraction is the element-wise twin of addition: match shapes, nest two loops, and subtract corresponding entries — expecting negatives when B wins a cell. Master the 3×3 and 2×2 samples so you can generalize sizes on demand.

Practice both examples above, then continue to matrix transpose for flipping rows and columns.

Same shape, then C[i][j] = A[i][j] - B[i][j] for every cell — and remember order matters.

💡 Best Practices

✅ Do

  • Confirm matching dimensions before coding
  • Keep A and B in the stated order
  • Use signed integers when negatives are possible
  • Dry-run one negative cell by hand
  • Quote O(m·n) for the classic pass

❌ Don’t

  • Subtract mismatched shapes
  • Assume A−B equals B−A
  • Use unsigned when signs matter
  • Confuse this with matrix multiplication
  • Ignore possible int overflow

Key Takeaways

Knowledge Unlocked

Five things to remember about matrix subtraction in C

Implement it the interview-friendly way.

5
Core concepts
= 02

Shape

Must match

Constraint
2 03

Loops

i, then j

Code
04

Signs

Negatives OK

Results
O 05

Cost

O(m·n)

Analysis

❓ Frequently Asked Questions

Subtraction works cell by cell like addition: same position in A minus same position in B. Matrix multiplication combines rows of A with columns of B and is a different operation entirely.
Yes. Each entry of A − B needs a matching entry in B, so both must be m×n for the same m and n.
Usually no. Subtraction is not commutative: B − A is the negative of A − B entrywise.
Yes. If A[i][j] < B[i][j], the difference at that cell is negative. int stores negatives fine within range.
Subtracting two large ints can still overflow signed int in edge cases. Use wider types if inputs can be huge.
Each of the m·n entries is computed once: O(m·n) time and O(1) extra space besides the output matrix.
A − B is the same as A + (−B) entrywise. The loop structure matches addition; only the operator changes.
Avoid unsigned for differences if negatives are possible — wraparound would hide underflow.

Did you Know? 🔊

Matrix subtraction is entrywise like addition: (A − B)ij = Aij − Bij. It is the same as adding A and (−B). The two matrices must have the same shape.

Continue to Matrix Transpose

Learn how to transpose a matrix by swapping rows and columns in C.

Matrix Transpose tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful