ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-202 min read

Add two matrices in C using 2D arrays and nested loops. Includes dimension checks, code implementation, and element-wise addition trace.

Matrix Addition Rule

Two matrices A and B can be added if and only if they have the same dimensions (R × C). The result matrix C has entries:

text (ISO Standard)
C[i][j] = A[i][j] + B[i][j]

Complete C Implementation

c (ISO Standard)
#include <stdio.h>

#define ROWS 3
#define COLS 3

void addMatrices(int A[ROWS][COLS], int B[ROWS][COLS], int result[ROWS][COLS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            result[i][j] = A[i][j] + B[i][j];
        }
    }
}

void printMatrix(int matrix[ROWS][COLS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%3d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int A[ROWS][COLS] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    int B[ROWS][COLS] = {
        {9, 8, 7},
        {6, 5, 4},
        {3, 2, 1}
    };

    int sum[ROWS][COLS];
    addMatrices(A, B, sum);

    printf("Matrix A + Matrix B Result:\n");
    printMatrix(sum);

    return 0;
}

Sample Output

text (ISO Standard)
Matrix A + Matrix B Result:
 10  10  10 
 10  10  10 
 10  10  10 

Complexity Analysis

  • Time Complexity: O(R × C) proportional to total elements.
  • Space Complexity: O(R × C) to store result array.

Related C Examples & Tutorials