Definition
Cij = Aij + Bij
Add corresponding entries when shapes match.
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.
Cij = Aij + Bij
Add corresponding entries when shapes match.
m × n
Addition is defined only when row and column counts match.
M[i][j]
Store each matrix as int M[ROWS][COLS] in interview C.
Rows × cols
Outer i over rows, inner j over columns.
3×3 sum
See Matrix 1, Matrix 2, and the resultant sum instantly.
Add & print
Separate routines for adding and displaying keep main clean.
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.
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.
Each cell adds independently.
Matching dimensions before any arithmetic.
One pass over every entry.
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.
Given two matrices of the same dimensions, compute their element-wise sum and optionally print all three matrices.
/* 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]]
*/ | Item | Type | Description |
|---|---|---|
mat1, mat2 | 2D arrays | Input matrices of identical shape. |
result | 2D array | Output matrix; filled entrywise. |
| Dimensions | ints / macros | Fixed 3, or ROWS/COLS macros. |
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] | Approach | Idea | Extra space |
|---|---|---|
| 2D array + nested loops | Classic interview solution | Output matrix only |
| Flat buffer + strides | i * COLS + j indexing | Same; more flexible shapes |
| Goal | Pattern |
|---|---|
| Add entry | result[i][j] = mat1[i][j] + mat2[i][j]; |
| Row-major visit | for (i...) for (j...) |
| Print cell | printf("%d ", matrix[i][j]); |
| End row | printf("\\n"); after the inner loop |
| Generalize size | #define ROWS 2 / #define COLS 2 |
Related matrix operations — only addition and subtraction share the same shape rule and nested-loop shape.
A+BSame shape; entrywise sum
A-BSame shape; entrywise difference
A×BNeeds A cols == B rows; different algorithm
shape firstState matching dimensions before coding loops
Reach for matrix addition when 2D indexing and entrywise work matter.
First 2D-array problem before multiplication or transpose.
Pixel or tile grids often add corresponding cells.
Builds intuition before scalar multiply and product rules.
Split add vs print for cleaner interview code.
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.
Uses the same 3×3 integers as Example 1. Press the button to print Matrix 1, Matrix 2, and the sum.
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.
Fixed-size 3×3 helpers for add and display.
add_matrices fills the result; display_matrix prints any 3×3 grid. Sample data matches the classic walkthrough.
#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;
} 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.
Same arithmetic with macros so sizes are easy to change.
Useful when an interviewer asks you to generalize dimensions before fixing them at 3.
#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;
} ROWS and COLS make it obvious where to change sizes later; the arithmetic inside the loops is unchanged.
Fixed-size arrays already match; for dynamic sizes, verify rows and columns first.
For each row i and column j, assign result[i][j] = mat1[i][j] + mat2[i][j].
Print entries with spaces and a newline after each row.
For the sample 3×3 inputs, every entry of the result is 10.
Trace one cell, then note that every other cell follows the same rule.
| Position | A | B | A + B |
|---|---|---|---|
[0][0] | 1 | 9 | 10 |
[0][1] | 2 | 8 | 10 |
[1][1] | 5 | 5 | 10 |
[2][2] | 9 | 1 | 10 |
Nine independent additions produce the all-10 result matrix — nested loops simply schedule them in row-major order.
Where matrix-addition thinking shows up beyond the interview prompt.
Build fluency with M[i][j] row/column access.
Example: same loops reused for printing grids.
Outer rows, inner columns — classic interview structure.
Example: for i wrapping for j.
Teaches validating dimensions before arithmetic.
Example: reject mismatched dynamic input.
Once addition is solid, product algorithms are easier to contrast.
Example: next matrix tutorials in the chain.
Separate add and print for readable main.
Example: add_matrices + display_matrix.
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.
Why this approach earns interview points.
One assignment per cell — easy to write and defend.
You must touch every entry; O(m·n) is necessary and sufficient.
Add and print routines keep demonstration code tidy.
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.
Small habits that keep matrix-addition code clean in interviews.
Say both matrices are m × n before writing loops.
Consistent naming prevents off-by-one mix-ups.
Always print \n after the inner loop for rectangular output.
Helpers make dry runs and follow-up edits easier.
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.
Mistakes that commonly break matrix-addition solutions in C.
Adding differently sized matrices is undefined.
→ Validate row and column counts before looping.
Treating columns as the outer loop without adjusting bounds causes out-of-range access.
→ Keep outer = rows, inner = columns unless you intentionally transpose.
Printing everything on one line hides the matrix structure.
→ printf("\\n") after each completed row.
Two large int entries can overflow when summed.
→ Use a wider type when the problem allows huge values.
Product needs a third loop over the shared dimension.
→ Addition never mixes different positions.
Most bugs are indexing and type issues, not the addition formula itself.
Never add matrices with different row or column counts.
Still one nested-loop pattern with bounds of 1.
Summing two large int entries can overflow; consider long long.
Call printf("\\n") after each row for rectangular layout.
Adding a zero matrix leaves the other unchanged — good sanity check.
Read both matrices with nested loops, then verify shared dimensions.
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.
| Sample | Result highlight |
|---|---|
| 3×3 demo | Every entry of the sum is 10 |
| 2×2 demo | Result is [[5,5],[5,5]] |
Try these variations to lock in the pattern.
+ to - with the same loopsrows and cols into helpersi * COLS + jCij = Aij + Bij for all positions; shapes must match.Quick Takeaway: matching shapes, then result[i][j] = a[i][j] + b[i][j] for every cell — that is matrix addition in C.
| Operation | Time | Extra space |
|---|---|---|
Add two m × n matrices | O(m · n) | O(1) besides the output matrix |
Print an m × n matrix | O(m · n) | O(1) |
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.
O(m·n) complexity when askedint overflowImplement it the interview-friendly way.
Cij = Aij + Bij
DefinitionSame m × n
GuardNested for loops
PatternAdd + print
StructureO(m·n)
AnalysisAddition 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).
Learn how to divide two matrices element-wise with 2D arrays in C.
8 people found this page helpful