Definition
Entrywise
Each output cell is the sum of matching input cells.
Matrix addition combines matching cells: C[i][j] = A[i][j] + B[i][j], only when shapes match. This tutorial covers the rule, nested loops over int[][COLS], a live preview, worked C++ examples, edge cases, and complexity.
Entrywise
Each output cell is the sum of matching input cells.
m × n both
Addition is defined only when dimensions match.
Rows × cols
Outer loop rows, inner loop columns, visit each cell once.
All 10s
Classic demo: complementary matrices sum to 10.
Show sum
Run the 3×3 sample matrices in the browser.
Per add
Visit each of the m·n cells exactly once.
Matrix addition is entrywise: if A and B are both m × n, then C = A + B is also m × n with C[i][j] = A[i][j] + B[i][j].
In C++ interviews, matrices are usually int[][] style 2D arrays or vector<vector<int>>. Nested loops walk every position once; if shapes differ, addition is not defined.
It is the cleanest 2D indexing warm-up — and the foundation before subtraction, multiplication, and transpose problems.
Top-left adds to top-left — never mix cells.
Validate rows and columns before looping.
Access cells with matrix[i][j].
A + B = B + A for equal-sized matrices.
In short: if shapes match, walk every cell with nested loops and set C[i][j] = A[i][j] + B[i][j].
Given two equal-sized matrices A and B, build C where each cell is the sum of corresponding cells.
// [[1, 2], [3, 4]] + [[4, 3], [2, 1]] = [[5, 5], [5, 5]]
// Same shape required; different shape → not defined | Item | Type | Description |
|---|---|---|
A, B | int[][COLS] | Two matrices with the same shape. |
| Return / print | matrix / text | Result matrix C with entrywise sums. |
function add_matrices(A, B, rows, cols):
create matrix C of shape rows x cols
for i from 0 to rows - 1:
for j from 0 to cols - 1:
C[i][j] <- A[i][j] + B[i][j]
return C | Method | Idea | Notes |
|---|---|---|
| Nested loops | C[i][j] = A[i][j] + B[i][j] | Interview default — clear indexing |
| Fixed-size loops | Hard-code 2 or 3 | Handy for whiteboard dry-runs |
| Shape-safe helper | Validate then allocate | Return null (or throw) on mismatch |
| Goal | Pattern |
|---|---|
| Rows | rows = ROWS (or m.size()) |
| Columns | cols = COLS (or m[0].size()) |
| Add cell | result[i][j] = a[i][j] + b[i][j] |
| Traverse | for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) |
| Print row | std::cout << x << " " per cell |
| Shape check | Same row and column counts for both matrices |
Same entrywise rule — pick the form that fits the interview.
i, j indexingClearest story for whiteboards
for i < 2Handy for 2×2 dry-runs
null on mismatchValidate before allocating
shape firstState the dimension rule before coding
Reach for matrix addition when 2D indexing and entrywise work matter.
Nested loops plus list-of-lists indexing.
First matrix operation before multiply / transpose.
Same pattern as combining equal-sized grids.
Shift from digit loops to 2D structures.
Different shape rules — do not confuse the two.
Key benefit: one short 2D problem that locks in indexing, shape validation, and O(m·n) thinking.
Uses the same 3×3 sample matrices as Example 1. Click to display Matrix 1, Matrix 2, and the result.
Three complete C++ programs — 3×3 helpers, compact 2×2, and a dimension-safe adder. Click View Output to reveal sample console results.
Reusable add and display helpers for a 3×3 pair.
Helper functions for addition and display — beginner-friendly and interview-friendly.
#include <iostream>
void addMatrices(const int mat1[][3], const int mat2[][3], int result[][3], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
void displayMatrix(const char* title, const int matrix[][3], int rows, int cols) {
std::cout << title << "\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
}
int main() {
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 resultMatrix[3][3];
addMatrices(matrix1, matrix2, resultMatrix, 3, 3);
displayMatrix("Matrix 1:", matrix1, 3, 3);
std::cout << "\n";
displayMatrix("Matrix 2:", matrix2, 3, 3);
std::cout << "\n";
displayMatrix("Resultant Matrix:", resultMatrix, 3, 3);
return 0;
} The key line is mat1[i][j] + mat2[i][j]. Nested loops visit every matching position once; the print helper formats each row for the console.
Same logic on a smaller 2×2 dry-run.
Fixed-size loops — great for quick whiteboard checks.
#include <iostream>
void addMatrices2x2(const int a[][2], const int b[][2], int result[][2]) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
}
void printMatrix(const char* title, const int m[][2]) {
std::cout << title << "\n";
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
std::cout << m[i][j] << " ";
}
std::cout << "\n";
}
}
int main() {
int a[2][2] = {
{ 1, 2 },
{ 3, 4 },
};
int b[2][2] = {
{ 4, 3 },
{ 2, 1 },
};
int c[2][2];
addMatrices2x2(a, b, c);
printMatrix("A", a);
std::cout << "\n";
printMatrix("B", b);
std::cout << "\n";
printMatrix("A + B", c);
return 0;
} Even with fixed size 2×2, the pattern is identical: loop over rows and columns and add matching entries.
Reject mismatched dimensions before adding.
Checks null/empty input and matching dimensions, then adds.
#include <iostream>
#include <string>
#include <vector>
using Matrix = std::vector<std::vector<int>>;
bool sameShape(const Matrix& a, const Matrix& b) {
if (a.empty() || b.empty() || a.size() != b.size()) {
return false;
}
if (a[0].empty() || a[0].size() != b[0].size()) {
return false;
}
for (size_t i = 0; i < a.size(); i++) {
if (a[i].size() != a[0].size() || b[i].size() != a[0].size()) {
return false;
}
}
return true;
}
bool addMatricesSafe(const Matrix& a, const Matrix& b, Matrix& result) {
if (!sameShape(a, b)) {
return false;
}
size_t rows = a.size();
size_t cols = a[0].size();
result.assign(rows, std::vector<int>(cols));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return true;
}
std::string matrixToString(const Matrix* m) {
if (m == nullptr) {
return "null";
}
std::string s = "[";
for (size_t i = 0; i < m->size(); i++) {
if (i > 0) s += ", ";
s += "[";
for (size_t j = 0; j < (*m)[i].size(); j++) {
if (j > 0) s += ", ";
s += std::to_string((*m)[i][j]);
}
s += "]";
}
s += "]";
return s;
}
int main() {
Matrix okInA = { { 1, 2 }, { 3, 4 } };
Matrix okInB = { { 4, 3 }, { 2, 1 } };
Matrix badInA = { { 1, 2 } };
Matrix badInB = { { 1, 2 }, { 3, 4 } };
Matrix ok;
Matrix* okPtr = addMatricesSafe(okInA, okInB, ok) ? &ok : nullptr;
Matrix bad;
Matrix* badPtr = addMatricesSafe(badInA, badInB, bad) ? &bad : nullptr;
std::cout << matrixToString(okPtr) << "\n";
std::cout << matrixToString(badPtr) << "\n";
return 0;
} Shape checks catch mismatched dimensions before any addition. Returning null (or throwing) is clearer than silent index errors.
If row or column counts differ, stop.
For each i, j set C[i][j] = A[i][j] + B[i][j].
Print each row on its own line.
C has the same shape as A and B.
Trace each cell for [[1, 2], [3, 4]] + [[4, 3], [2, 1]].
| (i, j) | A | B | C |
|---|---|---|---|
(0, 0) | 1 | 4 | 5 |
(0, 1) | 2 | 3 | 5 |
(1, 0) | 3 | 2 | 5 |
(1, 1) | 4 | 1 | 5 |
Result: [[5, 5], [5, 5]].
Where matrix addition shows up beyond the interview prompt.
2D indexing with a one-line cell formula.
Example: write add_matrices(A, B).
Outer row / inner column with a visual result.
Example: 3×3 all-10s demo.
Combine equal-sized 2D arrays entrywise.
Example: add two intensity maps.
Master shape rules before harder matrix ops.
Example: next up: division / multiply.
Practice rejecting mismatched shapes.
Example: Example 3 above.
State O(m·n) when asked about cost.
Example: one add per cell.
Pro Tip: say “same shape, entrywise sum” before writing a single loop.
Why this pattern works well in interviews and classwork.
One cell rule: C[i][j] = A[i][j] + B[i][j].
Exactly m·n additions for an m×n pair.
2×2 examples fit on a whiteboard in seconds.
Same traversal pattern for subtraction and more.
Pro Tip: lead with nested loops; mention a shape-safe helper if asked about robustness.
Small habits that keep matrix-addition solutions interview-ready.
Say “same m×n required” before coding loops.
Append a new row list each outer iteration — avoid shared references.
Four cells catch off-by-one bugs fast.
Keep matrix layout readable in console demos.
Interviewers often ask complexity right after the code.
Pro Tip: allocate with vector<vector<int>>(rows, vector<int>(cols)) so rows and columns are sized upfront.
Mistakes that commonly break matrix-addition solutions.
Adding matrices with different sizes.
→ Validate rows and columns first.
Reusing one row buffer incorrectly for every row corrupts updates.
→ Prefer rectangular storage and check matching row/column sizes before adding.
One row shorter than others causes index errors.
→ Check every row length equals cols.
Wrong index order corrupts rectangular matrices.
→ Keep i = row, j = column consistently.
Using row·column products for addition.
→ Addition is entrywise only.
Most matrix-addition bugs come from shape assumptions and indexing mistakes.
Never add matrices with different row or column counts.
Validate each row length before indexing.
Bad ranges skip cells or raise IndexError.
Decide whether [] + [] is allowed; guard empty rows.
Still uses the same formula — one addition.
Addition works the same for negative integers.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
C[i][j] = A[i][j] + B[i][j] only when dimensions match.m*n.Quick Takeaway: same shape required; add matching cells with nested loops in O(m·n).
| 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) |
| Shape validation | O(m) row checks | O(1) |
Matrix addition is entrywise: matching cells add when shapes match. Use nested loops over list-of-lists, validate dimensions, and state O(m·n) complexity.
Practice the three examples above, then continue to matrix division for the next 2D operation.
Same shape first, then C[i][j] = A[i][j] + B[i][j] — never confuse this with multiplication.
Add matrices the interview-friendly way.
Entrywise sum
DefinitionSame m × n
ConstraintRows then cols
Codeint[][COLS]
C++O(m·n)
AnalysisMatrix addition is entrywise: (A+B)ij = Aij + Bij. It is valid only when both matrices have the same number of rows and columns.
Learn how to divide two matrices entrywise with the same nested-loop pattern.
8 people found this page helpful