- Rule
- Only
a11andb11combine intoc11.
Perform Matrix Addition in C
What you’ll learn
- The rule Cij = Aij + Bij for matrices of the same size.
- How to implement add and print helpers with nested
forloops over rows and columns. - Two complete programs: a classic 3×3 demo and a smaller 2×2 variant, plus a browser live preview for the 3×3 sample.
Overview
Matrix addition is the entry-by-entry sum of two matrices of identical shape. In C you typically represent each matrix as a 2D array and fill the result with one nested loop nest.
Two programs
The reference 3×3 sample and a compact 2×2 illustration.
Live preview
Runs the same arithmetic as the first program on the built-in sample matrices.
Rigor
Shape rules, complexity, and realistic interview follow-ups in the FAQ.
Prerequisites
Arrays, nested loops, and formatted output with printf.
#include <stdio.h>,int main(void), and 2D array declarations such asint M[3][3].- Comfortable indexing with
M[i][j]whereiis the row andjis the column.
What is matrix addition?
If A and B are both m × n matrices, their sum C is the m × n matrix with Cij = Aij + Bij for every valid row i and column j.
If the shapes differ, addition is not defined in ordinary linear algebra—your program should either require matching dimensions or report an error.
Formal definition
If A and B are both m × n matrices (same row and column counts), then C = A + B satisfies Cij = Aij + Bij for all valid i and j. The same entrywise rule applies to integer matrices.
[1 2; 3 4] + [4 3; 2 1] = [5 5; 5 5] — each position adds independently.
Intuition
Think of each cell as one independent slot: you never mix entries from different positions.
- Work
- An
m × nsum needsm·nscalar additions.
Takeaway: nested loops simply schedule those m·n additions in row-major (or any fixed) order.
Live preview
Uses the same 3×3 integers as the first C program below. Press the button to print Matrix 1, Matrix 2, and the sum (text layout mirrors typical console output).
Algorithm
Goal: given two matrices A and B of the same dimensions, produce C with C[i][j] = A[i][j] + B[i][j].
Confirm shape
Fixed-size arrays already encode matching dimensions. For dynamic sizes, verify row and column counts before adding.
Nested traversal
For each row index i and column index j, assign result[i][j] = mat1[i][j] + mat2[i][j].
Display (optional)
Print rows with spaces or tabs between entries and a newline after each row.
📜 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] Add two 3×3 matrices (program with explanation)
Classic interview layout: add_matrices fills the result, display_matrix prints any 3×3 grid. Sample data matches the reference 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;
} Explanation
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.
for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j)Row-major visit. Each pair (i,j) is handled exactly once.
printf("%d ", matrix[i][j]);Spacing. A space after each entry keeps columns aligned in simple console output.
Add two 2×2 matrices
Same pattern with smaller arrays: useful when an interviewer asks you to generalize dimensions verbally 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;
} Explanation
ROWS and COLS make it obvious where to change sizes later; the arithmetic inside the loops is unchanged.
Optimization and extensions
Large matrices. For many entries (m · n large), memory bandwidth dominates; cache-friendly traversal (row-major for row-major storage) helps. Parallel threads can partition rows when correctness rules allow.
General size. Pass rows and cols as parameters (and preferably use a single flat buffer plus strides if you need variable shapes in one binary).
Interview: start with the double loop and correct indexing; mention shape checks and complexity when asked.
❓ FAQ
🔄 Input / output notes
The first program uses compile-time matrices. For interactive input you would add nested scanf loops (or read from a file) before calling add_matrices, still checking that both inputs share the same dimensions.
Edge cases and pitfalls
Most bugs are indexing and type issues, not the addition formula itself.
Mismatched dimensions
Never add A and B with different row or column counts. Validate sizes when reading dynamic input.
Integer ranges
Summing two large int entries can overflow. Use a wider type (long long) if the problem allows huge entries.
Row endings
Call printf("\n") after each row so output matches the usual rectangular layout.
⏱️ Time and space complexity
| 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) |
Summary
- Definition:
Cij = Aij + Bijfor all positions; shapes must match. - Code: nested loops over rows and columns; optional separate routine to print.
- Complexity: linear in the number of entries
m · n.
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).
8 people found this page helpful
