Perform Matrix Addition in C

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

What You’ll Learn

Matrix addition is the entry-by-entry sum of two matrices of identical shape. This tutorial covers the shape rule, 2D arrays in C, nested loops, a live preview, algorithm steps, worked C examples (3×3 and 2×2), edge cases, and complexity.

Definition

Cij = Aij + Bij

Add corresponding entries when shapes match.

Same Shape

m × n

Addition is defined only when row and column counts match.

2D Arrays

M[i][j]

Store each matrix as int M[ROWS][COLS] in interview C.

Nested Loops

Rows × cols

Outer i over rows, inner j over columns.

Live Preview

3×3 sum

See Matrix 1, Matrix 2, and the resultant sum instantly.

Helpers

Add & print

Separate routines for adding and displaying keep main clean.

Introduction

Matrix addition combines two matrices of the same shape by adding entries in matching positions: Cij = Aij + Bij. If the shapes differ, addition is not defined in ordinary linear algebra.

In C interviews you typically declare 2D arrays, write nested for loops, and optionally extract add_matrices and display_matrix helpers.

Why it matters?

It is the simplest 2D-array warm-up: indexing, nested loops, and shape awareness — skills that carry into matrix subtraction, multiplication, and image-style grids.

Key Highlights

Entrywise Sum

Each cell adds independently.

Shape First

Matching dimensions before any arithmetic.

O(m·n)

One pass over every entry.

Not Multiply

Addition is not matrix multiplication.

In short: for matching m × n matrices, set result[i][j] = mat1[i][j] + mat2[i][j] for every row i and column j.

📝 Problem & Approach

Given two matrices of the same dimensions, compute their element-wise sum and optionally print all three matrices.

c
/* A = [[1,2,3],[4,5,6],[7,8,9]]
 * B = [[9,8,7],[6,5,4],[3,2,1]]
 * C[i][j] = A[i][j] + B[i][j]
 * C = [[10,10,10],[10,10,10],[10,10,10]]
 */

Inputs & Outputs

ItemTypeDescription
mat1, mat22D arraysInput matrices of identical shape.
result2D arrayOutput matrix; filled entrywise.
Dimensionsints / macrosFixed 3, or ROWS/COLS macros.

Minimal workflow

Pseudocode
function add_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

ApproachIdeaExtra space
2D array + nested loopsClassic interview solutionOutput matrix only
Flat buffer + stridesi * COLS + j indexingSame; more flexible shapes

⚡ Quick Reference

GoalPattern
Add entryresult[i][j] = mat1[i][j] + mat2[i][j];
Row-major visitfor (i...) for (j...)
Print cellprintf("%d ", matrix[i][j]);
End rowprintf("\\n"); after the inner loop
Generalize size#define ROWS 2 / #define COLS 2

📋 Addition vs Subtraction vs Multiplication

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

Addition
A+B

Same shape; entrywise sum

Subtraction
A-B

Same shape; entrywise difference

Multiply
A×B

Needs A cols == B rows; different algorithm

Interview tip
shape first

State matching dimensions before coding loops

Context

When This Problem Shows Up

Reach for matrix addition when 2D indexing and entrywise work matter.

  1. Interview warm-ups

    First 2D-array problem before multiplication or transpose.

  2. Image / grid math

    Pixel or tile grids often add corresponding cells.

  3. Linear algebra basics

    Builds intuition before scalar multiply and product rules.

  4. Helper-function practice

    Split add vs print for cleaner interview code.

  5. Not for mismatched shapes

    Refuse or error when dimensions differ.

Key benefit: a tiny nested-loop pattern that proves you can index 2D arrays correctly before harder matrix work.

🔮 Live Preview

Uses the same 3×3 integers as Example 1. Press the button to print Matrix 1, Matrix 2, and the sum.

Matches the sample matrices in code example 1.

Live result
Press “Show 3×3 sum”.

Examples Gallery

Two complete C programs — a classic 3×3 demo and a smaller 2×2 variant with size macros. Click View Output to reveal sample console results.

📚 Getting Started

Fixed-size 3×3 helpers for add and display.

Example 1 — Add Two 3×3 Matrices

add_matrices fills the result; display_matrix prints any 3×3 grid. Sample data matches the classic walkthrough.

c
#include <stdio.h>

void add_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 ", matrix[i][j]);
        }
        printf("\n");
    }
}

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

    add_matrices(matrix1, matrix2, result_matrix);

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

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

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

    return 0;
}

How It Works

The core is result[i][j] = mat1[i][j] + mat2[i][j] inside the nested loops. display_matrix walks the same indices but prints instead of assigning.

📈 Practical Patterns

Same arithmetic with macros so sizes are easy to change.

Example 2 — Add Two 2×2 Matrices

Useful when an interviewer asks you to generalize dimensions before fixing them at 3.

c
#include <stdio.h>

#define ROWS 2
#define COLS 2

void add_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];

    add_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 and COLS make it obvious where to change sizes later; the arithmetic inside the loops is unchanged.

🧠 How the Algorithm Adds Matrices

1

Confirm shape

Fixed-size arrays already match; for dynamic sizes, verify rows and columns first.

Guard
2

Nested traversal

For each row i and column j, assign result[i][j] = mat1[i][j] + mat2[i][j].

Add
3

Display (optional)

Print entries with spaces and a newline after each row.

Print
=

Sum ready

For the sample 3×3 inputs, every entry of the result is 10.

🔎 Worked Walkthrough — Top-Left of the 3×3 Sample

Trace one cell, then note that every other cell follows the same rule.

PositionABA + B
[0][0]1910
[0][1]2810
[1][1]5510
[2][2]9110

Nine independent additions produce the all-10 result matrix — nested loops simply schedule them in row-major order.

Use Cases

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

1. 2D Indexing Practice

Build fluency with M[i][j] row/column access.

Example: same loops reused for printing grids.

2. Nested Loop Warm-Ups

Outer rows, inner columns — classic interview structure.

Example: for i wrapping for j.

3. Shape Awareness

Teaches validating dimensions before arithmetic.

Example: reject mismatched dynamic input.

4. Path to Multiplication

Once addition is solid, product algorithms are easier to contrast.

Example: next matrix tutorials in the chain.

5. Helper Functions

Separate add and print for readable main.

Example: add_matrices + display_matrix.

6. Macro Dimensions

Parameterize sizes so the same logic scales to 2×2 or N×N.

Example: ROWS / COLS in Example 2.

Pro Tip: say “same shape, entrywise sum, O(m·n)” before writing loops — interviewers like that framing.

Advantages

Why this approach earns interview points.

  1. 1. Dead-Simple Correctness

    One assignment per cell — easy to write and defend.

  2. 2. Optimal Asymptotics

    You must touch every entry; O(m·n) is necessary and sufficient.

  3. 3. Clear Helper Split

    Add and print routines keep demonstration code tidy.

  4. 4. Easy to Generalize

    Change macros or pass rows/cols for other sizes.

Pro Tip: mention overflow and shape checks as follow-ups even if the sample uses tiny fixed arrays.

Usage Tips

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

  1. 1. State Shape First

    Say both matrices are m × n before writing loops.

  2. 2. Keep i = Row, j = Column

    Consistent naming prevents off-by-one mix-ups.

  3. 3. Newline After Each Row

    Always print \n after the inner loop for rectangular output.

  4. 4. Separate Add and Print

    Helpers make dry runs and follow-up edits easier.

  5. 5. Mention Overflow

    Large int entries may need long long for the sum.

Pro Tip: dry-run one cell on paper (table above) before coding the full nest — it locks in the indexing story.

Common Pitfalls

Mistakes that commonly break matrix-addition solutions in C.

  1. 1. Mismatched Dimensions

    Adding differently sized matrices is undefined.

    → Validate row and column counts before looping.

  2. 2. Swapping i and j Mentally

    Treating columns as the outer loop without adjusting bounds causes out-of-range access.

    → Keep outer = rows, inner = columns unless you intentionally transpose.

  3. 3. Forgetting Row Newlines

    Printing everything on one line hides the matrix structure.

    printf("\\n") after each completed row.

  4. 4. Integer Overflow

    Two large int entries can overflow when summed.

    → Use a wider type when the problem allows huge values.

  5. 5. Confusing With Multiplication

    Product needs a third loop over the shared dimension.

    → Addition never mixes different positions.

Edge Cases

Most bugs are indexing and type issues, not the addition formula itself.

Shape

Mismatched dimensions

Never add matrices with different row or column counts.

1×1

Single cell

Still one nested-loop pattern with bounds of 1.

Overflow

Integer ranges

Summing two large int entries can overflow; consider long long.

Print

Row endings

Call printf("\\n") after each row for rectangular layout.

Zeros

Zero matrix

Adding a zero matrix leaves the other unchanged — good sanity check.

Input

Dynamic scanf

Read both matrices with nested loops, then verify shared dimensions.

🔄 Input / Output Notes

The sample programs use compile-time matrices. For interactive input, add nested scanf loops before calling add_matrices, still checking that both inputs share the same dimensions.

SampleResult highlight
3×3 demoEvery entry of the sum is 10
2×2 demoResult is [[5,5],[5,5]]

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Read matrices from stdin

  • Ask for rows/cols, then scan both grids
  • Reject mismatched shapes

2. Matrix subtraction

  • Change + to - with the same loops
  • Print A, B, and A − B

3. Parameterize size

  • Pass rows and cols into helpers
  • Support any fixed max capacity you declare

4. Flat array version

  • Store entries in a 1D buffer
  • Index with i * COLS + j

Notes

  • Definition. Cij = Aij + Bij for all positions; shapes must match.
  • Addition is commutative and associative entrywise.
  • Nested loops over rows and columns; optional separate print helper.
  • Not the same algorithm as matrix multiplication.

Quick Takeaway: matching shapes, then result[i][j] = a[i][j] + b[i][j] for every cell — that is matrix addition in C.

⏱️ Time and Space Complexity

OperationTimeExtra space
Add two m × n matricesO(m · n)O(1) besides the output matrix
Print an m × n matrixO(m · n)O(1)
Wrap Up

🎉 Conclusion

Matrix addition is the cleanest entry into 2D arrays in C: confirm matching shapes, nest two loops, and assign the entrywise sum. Master the 3×3 helpers and the macro-based 2×2 variant so you can scale sizes on demand.

Practice both examples above, then continue to matrix division for the next operation in the chain.

Matching shapes, then result[i][j] = a[i][j] + b[i][j] for every cell — that is the whole algorithm.

💡 Best Practices

✅ Do

  • Confirm matching dimensions before adding
  • Use nested loops with clear row/column indices
  • Split add and print into helpers
  • Print a newline after each row
  • State O(m·n) complexity when asked

❌ Don’t

  • Add matrices of different shapes
  • Confuse addition with matrix multiplication
  • Omit row newlines in console output
  • Ignore possible int overflow
  • Hard-code sizes without mentioning how to generalize

Key Takeaways

Knowledge Unlocked

Five things to remember about matrix addition in C

Implement it the interview-friendly way.

5
Core concepts
= 02

Shape

Same m × n

Guard
[] 03

Code

Nested for loops

Pattern
fn 04

Helpers

Add + print

Structure
O 05

Complexity

O(m·n)

Analysis

❓ Frequently Asked Questions

They must have the same dimensions: the same number of rows and the same number of columns. Then each entry of the sum is the sum of the corresponding entries.
The usual interview approach is a 2D array, for example int A[ROWS][COLS], or a flat array with manual indexing i * COLS + j for row-major layout.
Yes: A + B = B + A entrywise. Associativity (A + B) + C = A + (B + C) holds as well.
Same shape requirement: C_ij = A_ij - B_ij. It is equivalent to adding A and (-B).
For an m×n matrix, adding two matrices touches each element once: O(m·n) time and O(1) extra space aside from storing the result.
You need to visit every row index i and column index j to compute result[i][j] = mat1[i][j] + mat2[i][j]. Two loops (outer rows, inner columns) match that traversal.
No. Addition is entrywise with matching shapes. Multiplication combines rows of A with columns of B and needs A cols == B rows.
Use macros or parameters for ROWS and COLS (as in the 2×2 example), or pass row/column counts into helper functions.

Did you Know? 🔊

Addition of real matrices is entrywise: (A+B)ij = Aij + Bij. It is only defined when A and B share the same shape (same row and column counts).

Continue to Matrix Division

Learn how to divide two matrices element-wise with 2D arrays in C.

Matrix Division 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