Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Matrix Addition in C
Add two 2D arrays element by element with nested loops, read them safely from the keyboard, and see how the same idea powers sensor and image processing in embedded C programming.
Matrix Addition in C: The Idea
Matrix addition in C means creating a third 2D array in which every cell holds the sum of the two cells that sit at the same row and column in the input arrays. It is the simplest useful program you can write with a two-dimensional array, and it teaches the nested-loop pattern that every later matrix program in this free C programming course reuses. If you are learning through this free embedded C course, treat it as a warm-up for bigger jobs such as combining two sensor frames or blending image buffers.
What You Will Learn
- The mathematical rule for adding matrices and why the orders must match
- The nested-loop pattern: outer loop on rows, inner loop on columns
- A complete, compile-ready program with real output
- Reading a matrix from the keyboard and rejecting bad input
- Saturating addition for 8-bit data, a common embedded C programming need
- Typical mistakes and how to avoid them
Prerequisites
Finish the previous lecture on 2D array initialization first. You should know how to declare int m[2][3], how row-major storage works, and how a for loop runs. Any C11 compiler such as gcc will do.
The Rule for Adding Matrices
A matrix is just a rectangular table of numbers, which in C is a 2D array. Two matrices can be added only when they have the same order, meaning the same number of rows and the same number of columns. The result has that same order too, and each result cell is computed as:
sum[i][j] = a[i][j] + b[i][j]
There is no mixing between cells. The value at row 1, column 2 of the answer depends only on row 1, column 2 of the two inputs. That independence is the reason matrix addition is easy to run in parallel on DSPs and GPUs, and also why it is a gentle first exercise.
Cell-by-cell addition of two 2×3 matrices
| Matrix A | Matrix B | Result sum |
|---|---|---|
| 10 20 30 | 1 2 3 | 11 22 33 |
| 40 50 60 | 4 5 6 | 44 55 66 |
Visiting Every Cell with Nested Loops
To touch every element of a 2D array you need two counters: one for the row, one for the column. The outer loop picks a row, and the inner loop sweeps across all columns of that row before the outer loop moves on. Because C stores rows one after another, this order also walks memory in a straight line, which is the fastest access pattern.
Loop order: outer loop = row i, inner loop = column j
Number of Operations
For an R by C matrix the loop body runs R times C times. A 2×3 matrix needs 6 additions, a 100×100 image block needs 10,000. Doubling both sides quadruples the work.
Program 1: Matrix Addition with Fixed Data
We begin with constants so the output is predictable and you can focus on the loop structure. Dimensions are named with #define, which is the habit you want for embedded C programming.
/* matadd.c - add two 2x3 matrices */
#include <stdio.h>
#define ROWS 2
#define COLS 3
int main(void)
{
int a[ROWS][COLS] = { {10, 20, 30}, {40, 50, 60} };
int b[ROWS][COLS] = { { 1, 2, 3}, { 4, 5, 6} };
int sum[ROWS][COLS];
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLS; j++)
sum[i][j] = a[i][j] + b[i][j];
printf("sum:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++)
printf("%5d", sum[i][j]);
printf("\n");
}
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o matadd matadd.c
$ ./matadd
sum:
11 22 33
44 55 66
The format %5d prints each number in a field five characters wide, which lines the columns up neatly. Changing ROWS and COLS at the top is the only edit needed to work with a different size, because every loop and declaration uses those names.
Program 2: Matrix Addition from Keyboard Input
Real programs rarely have the data baked in. The version below reads both matrices with scanf. Many beginner tutorials ignore the return value of scanf, but a robust program checks it: scanf returns the number of items it converted, so anything other than 1 means the user typed something that was not an integer.
/* matadd_in.c - matrix addition with checked input */
#include <stdio.h>
#define ROWS 2
#define COLS 3
static int read_matrix(const char *name, int m[ROWS][COLS])
{
printf("Enter %s (%dx%d), row by row:\n", name, ROWS, COLS);
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLS; j++)
if (scanf("%d", &m[i][j]) != 1)
return -1; /* bad or missing input */
return 0;
}
int main(void)
{
int a[ROWS][COLS], b[ROWS][COLS], sum[ROWS][COLS];
if (read_matrix("A", a) || read_matrix("B", b)) {
printf("input error\n");
return 1;
}
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLS; j++)
sum[i][j] = a[i][j] + b[i][j];
printf("A + B =\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++)
printf("%5d", sum[i][j]);
printf("\n");
}
return 0;
}
Run it with good input, then with a bad value:
$ printf '1 2 3\n4 5 6\n10 20 30\n40 50 60\n' | ./matadd_in
Enter A (2x3), row by row:
Enter B (2x3), row by row:
A + B =
11 22 33
44 55 66
$ printf '1 2 x' | ./matadd_in
Enter A (2x3), row by row:
input error
Two things are worth noticing. First, read_matrix declares its parameter as int m[ROWS][COLS]. When a 2D array is passed to a function, the function must still know the column count, for exactly the reason we met in the last lecture: it needs the row stride. Second, the function modifies the caller’s array directly, because arrays are passed by address.
Matrix Addition in C for Embedded Systems
Where does this show up in firmware? Think of a thermal camera that produces an 8×8 grid of temperatures. Adding a stored offset grid corrects each pixel. Or consider an 8-bit image where you brighten the picture by adding a boost matrix. In these cases the data type is often uint8_t, and plain addition has a trap: 250 + 10 does not give 260, it wraps around to 4. For brightness you want saturation, meaning the value sticks at 255.
/* satadd.c - saturating addition for 8-bit data */
#include <stdio.h>
#include <stdint.h>
#define ROWS 2
#define COLS 3
int main(void)
{
uint8_t base[ROWS][COLS] = { {200, 100, 50}, {250, 10, 0} };
uint8_t boost[ROWS][COLS] = { { 80, 60, 50}, { 10, 10, 0} };
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
unsigned s = base[i][j] + boost[i][j]; /* widen first */
uint8_t out = (s > 255u) ? 255u : (uint8_t)s;
printf("%4u", out);
}
printf("\n");
}
return 0;
}
$ ./satadd
255 160 100
255 20 0
The values 200 + 80 and 250 + 10 would overflow a byte, but the program widens to unsigned before adding and clamps the result to 255. This small habit prevents a whole class of visual glitches and sensor bugs.
| Data type | Behaviour on overflow | Use when |
|---|---|---|
| int (signed) | Undefined behaviour in C | Keep sums within range, or widen to a larger type |
| uint8_t / unsigned | Wraps around modulo 2^N | Hash and counter style math |
| Saturating (manual clamp) | Sticks at the maximum | Pixels, audio samples, sensor offsets |
Common Mistakes and Troubleshooting
| Mistake | What happens | Fix |
|---|---|---|
| Adding matrices of different order | Not defined mathematically; code reads past an array | Check dimensions before the loops |
| Forgetting to size the result array | Compile error or memory corruption | Declare sum with the same ROWS and COLS |
| Using one loop variable for both loops | Only part of the matrix is processed | Use i for rows and j for columns |
| Ignoring the return value of scanf | Garbage values are added silently | Test that scanf returned 1 |
| Missing column count in a function parameter | Compile error | Write int m[][COLS] or int m[ROWS][COLS] |
| Overflow on small integer types | Wrong or wrapped results | Widen first, then clamp or check |
Best Practices
- Name the dimensions with #define or a const so one edit changes the whole program.
- Write the result to a separate array when you can, so the inputs stay untouched and debugging is easier.
- Check scanf results, and always print the matrix after reading it while you test.
- Keep the inner loop on the column index to follow memory order.
- For fixed-size data in firmware, keep matrices static or global instead of large locals on a small stack.
- Validate sizes that arrive from outside the program, such as a packet header, before using them as loop limits.
Summary and Key Takeaways
- Only matrices of the same order can be added; the result keeps that order.
- The core statement is sum[i][j] = a[i][j] + b[i][j] inside two nested loops.
- Functions that accept 2D arrays must be told the column count.
- scanf returns the number of values read, and a robust program checks it.
- Small integer types need widening and clamping to avoid wrap-around.
Conclusion
Matrix addition is deliberately simple, and that is its value: the same two nested loops, with a slightly different body, will multiply and transpose matrices in the coming lectures of this free c tutorial. You also practiced three habits that matter in professional embedded C programming: named dimensions, checked input and overflow awareness.
Frequently Asked Questions
Can I add two matrices of different sizes in C?
No. Matrix addition is defined only for matrices of the same order. If the sizes differ you must reject the operation or pad the smaller one on purpose.
Why are two nested loops needed for matrix addition?
A 2D array has two indices, so one loop walks the rows and another walks the columns of each row to reach every cell exactly once.
Can I store the result back into the first matrix?
Yes, writing a[i][j] += b[i][j] works and saves memory. Keep a separate result array while learning so the original data survives.
How do I pass a 2D array to a function?
Declare the parameter with the column count, for example int m[][COLS]. The function needs it to compute where each row starts.
What is the time complexity of matrix addition?
It is proportional to the number of elements, rows times columns, so each doubling of both sides roughly quadruples the work.
Is matrix addition used in embedded systems?
Yes, for sensor offset correction, image brightness, filter kernels and any task that combines two equally shaped data grids.
Continue the Free C Tutorial
Next: matrix multiplication with three nested loops. Keep building your embedded C programming skills with the free C programming course on EmbeddedPathashala.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

1 Comment