Back

Key Programs For Addition of Two Matrix in C

18 Feb 2025
4 min read

Matrix addition is a fundamental operation in linear algebra, widely used in various fields such as computer graphics, machine learning, and scientific computing. Matrices are rectangular arrays of numbers arranged in rows and columns, powerful tools for representing and manipulating data in multiple dimensions. The addition of two matrix program in c involves combining two matrices of the same dimensions by adding their corresponding elements.  

In this article, we will explore how to use different methods to add two matrices using the C programming language, providing a detailed explanation of the algorithm, implementation, and examples.

What are Matrices?

A matrix is a rectangular array of numbers arranged in rows and columns. In C, matrices are represented as two-dimensional arrays. For matrix addition to be valid, both matrices must have the same dimensions (i.e., the same number of rows and columns).

The notation for matrix addition is as follows: 

Given two matrices A and B, both of size m×n, the matrix sum A+B is a matrix of the same size, with each element obtained by adding the corresponding elements from matrices A and B.

A+B=[aij+bij]mxn

where:

  • aij​ and bijj​ are the elements of matrices A and B at the i-th row and j-th column respectively.
  • m is the number of rows, and n is the number of columns in both matrices A and B.

Arrays in C

In C programming, matrices are implemented using arrays. A matrix can be represented as a 2D array, where each element is accessed using row and column indices.

Example:

In C, an array of size m×n is declared as:

int A[100][100]; // For a matrix A with 100 rows and 100 columns. 

You can access elements in the matrix using indices:

A[i][j] // Accesses the element at the i-th row and j-th column. 

Multidimensional Arrays in C

A multidimensional array in C is essentially an array of arrays. For matrix representation, the most common multidimensional array is a 2D array, which is used to store rows and columns of a matrix.

Example of a 2D Array:

To declare a 2D array in C:

int matrix[3][3]; // A 3x3 matrix.

You can store and access elements as follows:

matrix[0][0] = 1;  // First row, first column
matrix[2][2] = 5;  // Third row, third column

In the case of matrix addition, a typical process would look like:

int A[100][100], B[100][100], sum[100][100];
for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j) {
        sum[i][j] = A[i][j] + B[i][j]; // Element-wise addition
    }
}

Array of Structure in C

An array of structures in C is an array where each element is a structure. In the context of matrices, this could be used to store matrices in a more complex way, if you want to add extra metadata or properties to each matrix element.

Example:

Let’s say we have a structure that represents a matrix element with its value and an extra field, say a label:

struct MatrixElement {
    int value;
    char label[10];
};

Now, you can declare an array of structures:

struct MatrixElement A[100][100];  // 2D array of structure

You can assign values to the structure elements and access them like this:

A[0][0].value = 1;  // Set value of the first element
strcpy(A[0][0].label, "first");  // Assign a label to the first element

In the case of matrix addition, you could potentially use an array of structures to store both the values and labels, and then add only the values of corresponding matrix elements:

struct MatrixElement sum[100][100];
for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j) {
        sum[i][j].value = A[i][j].value + B[i][j].value;
    }
}

What is Matrix Addition?

Matrix addition is defined as the process of adding two matrix elements. Two matrices, A and B, must have the same number of rows and columns to be added. The resulting matrix C will also have the same dimensions, where each element is calculated as follows:

Cij = Aij + Bij

custom img

This operation is similar to adding algebraic expressions, where only like terms can be combined. In the case of matrices, only corresponding elements from the two matrices can be added together.

There are two conditions for adding matrices such as:

  • Both matrices must have the same number of rows.
  • Both matrices must have the same number of columns.

Properties of Matrix Addition 

The properties of two matrices addition include:

1. Commutative Property

Adding in any order does not affect the result. If A and B are matrices of the same dimensions, then A+B=B+A

This means that you can add matrices in any order, and the sum will remain the same.

2. Associative Property

The way in which matrices are grouped during addition does not affect the result. If A, B, and C are matrices of the same dimensions, then (A+B)+C=A+(B+C)

This allows for flexibility in how calculations are performed when adding multiple matrices.

3. Additive Identity

An additive identity, known as the zero matrix, results in the original matrix A when added to any matrix A. The zero matrix has all its elements equal to zero: A+0=A

This property ensures that adding a zero matrix does not change the value of the original matrix.

4. Additive Inverse

For every matrix A, there exists an additive inverse (denoted as −A) such that: A+(−A)=0.

Here, −A is the matrix where each element is the negation of the corresponding element in A. This property allows for the cancellation of matrices.

5. Compatibility with Scalar Multiplication Distributive Property 

When a matrix is multiplied by a scalar, the result can still be added to another matrix of the same dimension. If k is a scalar and A and B are matrices, then k(A+B)=kA+kB

This property shows how scalar multiplication interacts with matrix addition.

How to Create a Matrix in C Language?

Here are the ways to create a matrix in C language:

1. Matrix Using an Array

In C, a matrix can be represented as a 2D array (array of arrays). Here's an example of addition of two matrix in c using array:

Code 
#include <stdio.h>

int main() {
    // Define a 3x3 matrix using an array
    int matrix[3][3] = {
        {5, 10, 15},
        {20, 25, 30},
        {35, 40, 45}
    };

    // Print the matrix
    printf("Matrix created using an array:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Explanation
  • The matrix is defined as a two-dimensional array with three rows and three columns, initialised with specific values.
  • Nested loops iterate through each row (i) and column (j) of the matrix to print its elements. Each row is printed on a new line.
  • The output displays the matrix in a structured format.
Output
Matrix created using an array:
5 10 15 
20 25 30 
35 40 45 

2. Matrix Using a Nested Loop

It contains a 3x3 matrix and uses nested loops to print each element of the matrix

#include <stdio.h>

int main() {
    int matrix[3][3];
    
    // Initialize the matrix elements using nested loops
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            matrix[i][j] = (i + 1) * (j + 1); // Example initialization
        }
    }

    // Print the matrix
    printf("Matrix created using a nested loop:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Explanation
  • The two-dimensional array matrix is declared.
  • Nested loops are used to fill the matrix. Each element is calculated based on its row and column indices, specifically (i + 1) * (j + 1), resulting in a multiplication table format.
  • It prints each element of the matrix.
Output
Matrix created using a nested loop:
1 2 3 
2 4 6 
3 6 9

3. Matrix Using Dynamic Memory Allocation

Here’s an example of how to create a matrix using dynamic memory allocation in c:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int rows = 3, cols = 3;
    
    // Dynamic memory allocation for a matrix
    int **matrix = (int **)malloc(rows * sizeof(int *));
    for (int i = 0; i < rows; i++)
        matrix[i] = (int *)malloc(cols * sizeof(int));

    // Initialize the matrix elements
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = (i + j) * (i - j); // Example initialization
        }
    }

    // Print the matrix
    printf("Matrix created using dynamic memory allocation:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    // Free allocated memory
    for (int i = 0; i < rows; i++)
        free(matrix[i]);
    free(matrix);

    return 0;
}
Explanation
  • Memory for a two-dimensional array is allocated at runtime using malloc. An array of pointers (matrix) is created first, followed by allocating memory for each row.
  • Elements are initialised based on the formula (i + j) * (i - j), which produces varying values depending on the indices.
  • The nested loops print each element dynamically allocated matrix.
  • After usage, free() is called to deallocate memory for each row and then for the main pointer to prevent memory leaks.
  • The output displays the initialised values based on the defined logic.
Output
Matrix created using dynamic memory allocation:
0 -1 -2 
1 0 -1 
2 -1 0

C Program for Addition of Two Matrix

Here is the addition of two matrices program in c:

Code

#include <stdio.h>

int main() {
    int rows, cols;
    scanf("%d %d", &rows, &cols);
    
    int A[rows][cols], B[rows][cols], C[rows][cols];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &A[i][j]);
        }
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &B[i][j]);
        }
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            C[i][j] = A[i][j] + B[i][j];
            printf("%d ", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Explanation

  • The program uses two 2D arrays, m1 and m2, to store the elements of the two input matrices. The resulting matrix is stored in the result.  
  • The user is prompted to input the number of rows (r) and columns (c), followed by the elements of both matrices. 
  • The program adds the two matrices element by element and stores the result in the result matrix.

Output

//Input
2 3
1 2 3
4 5 6
7 8 9
10 11 12

//Output
8 10 12
14 16 18

C Program to Add Two Square Matrices

This program defines how to add two square matrices. A square matrix has an equal number of rows and columns.

#include <stdio.h>

int main() {
    int n;
    printf("Enter the size of the square matrix: ");
    scanf("%d", &n);

    int A[n][n], B[n][n], C[n][n];

    // Input elements of first square matrix
    printf("Enter elements of Matrix A:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &A[i][j]);
        }
    }

    // Input elements of second square matrix
    printf("Enter elements of Matrix B:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &B[i][j]);
        }
    }

    // Adding matrices A and B, storing result in C
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    // Output the resultant matrix
    printf("Resulting Matrix (A + B):\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%d ", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Explanation

  • The user inputs the size n for the square matrices A and B.
  • The program adds corresponding elements from A and B and stores the result in matrix C.
  • The resultant matrix is displayed after the addition.

Output

Enter the size of the square matrix: 2
Enter elements of Matrix A:
1 2
3 4
Enter elements of Matrix B:
5 6
7 8

C Program to Add Two Rectangular Matrices

This program adds two rectangular matrices where the number of rows and columns can vary. It ensures that both matrices have the same dimensions before performing the addition.

#include <stdio.h>

int main() {
    int r, c;
    printf("Enter the number of rows and columns for the matrices: ");
    scanf("%d %d", &r, &c);

    int A[r][c], B[r][c], C[r][c];

    // Input elements of the first rectangular matrix
    printf("Enter elements of Matrix A:\n");
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            scanf("%d", &A[i][j]);
        }
    }

    // Input elements of the second rectangular matrix
    printf("Enter elements of Matrix B:\n");
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            scanf("%d", &B[i][j]);
        }
    }

    // Adding matrices A and B, storing result in C
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    // Output the resultant matrix
    printf("Resulting Matrix (A + B):\n");
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            printf("%d ", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Explanation

  • The user inputs the number of rows (r) and columns (c) for the rectangular matrices A and B.
  • Similar to the square matrix program, corresponding elements from A and B are added and stored in matrix C.
  • The resulting matrix is printed.

Output

Enter the number of rows and columns for the matrices: 2 3
Enter elements of Matrix A:
1 2 3
4 5 6
Enter elements of Matrix B:
7 8 9
10 11 12

Algorithm 

Here is the Step-by-step algorithm to add two matrices:

  • Enter the number of rows and columns for both matrices. Ensure they have the same dimensions.
  • Declare two matrices for input and one matrix to store the result of the addition.
  • Use nested loops to read elements for both matrices from the user.
  • Use nested loops to iterate through each element of both matrices.
  • Add corresponding elements and store the result in the resulting matrix.
  • Print the resulting matrix containing both input matrices' corresponding elements' sums.

Flowchart for Matrix Addition

custom img

Implementation of Addition Matrix in C

Here is the implementation for addition of two matrix in c using 2d array

#include <stdio.h>

int main() {
    int r, c;
    int mat1[100][100], mat2[100][100], sum[100][100];

    // Input dimensions
    printf("Enter number of rows: ");
    scanf("%d", &r);
    printf("Enter number of columns: ");
    scanf("%d", &c);

    // Input first matrix
    printf("Enter elements of Matrix 1:\n");
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < c; ++j) {
            printf("Element [%d][%d]: ", i, j);
            scanf("%d", &mat1[i][j]);
        }
    }

    // Input second matrix
    printf("Enter elements of Matrix 2:\n");
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < c; ++j) {
            printf("Element [%d][%d]: ", i, j);
            scanf("%d", &mat2[i][j]);
        }
    }

    // Adding matrices
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < c; ++j) {
            sum[i][j] = mat1[i][j] + mat2[i][j];
        }
    }

    // Output result
    printf("Sum of the two matrices:\n");
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < c; ++j) {
            printf("%d ", sum[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Input

Number of rows: 3
Number of columns: 3
Matrix 1:
0 1 2
3 4 5
6 7 8

Matrix 2:
9 10 11
12 13 14
15 16 17

Output

The sum of the two matrices:
9 11 13 
15 17 19 
21 23 25 

Explanation

  • The program starts by declaring variables for row and column counts and creating three matrices (mat1, mat2, and sum).
  • Input the number of rows and columns, followed by the elements of both matrices.
  • Nested loops iterate through each element, adding corresponding elements from mat1 and mat2, storing the result in sum.
  • Finally, the resulting matrix is printed to the console.

Complexity Analysis

  • Time Complexity: O(n2)
  • Space Complexity: O(n2)

Addition of Two Matrices in C Using Functions

Here is the addition of two matrix in c using functions:

#include <stdio.h>

void addMatrices(int rows, int cols, 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];
        }
    }
}

int main() {
    int rows, cols;

    // Input number of rows and columns
    printf("Enter number of rows and columns: ");
    scanf("%d %d", &rows, &cols);

    int A[rows][cols], B[rows][cols], result[rows][cols];

    // Input elements of first matrix
    printf("Enter elements of Matrix A:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &A[i][j]);
        }
    }

    // Input elements of second matrix
    printf("Enter elements of Matrix B:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &B[i][j]);
        }
    }

    // Call the function to add matrices
    addMatrices(rows, cols, A, B, result);

    // Output the result
    printf("Resulting Matrix (A + B):\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Explanation

  • The function addMatrices() takes the dimensions of the matrices (rows and cols), two matrices A and B, and a result matrix to store the sum of A and B.
  • In the main() function, the user inputs the matrices A and B, and the addition result is displayed using the addMatrices() function.

Output

Enter number of rows and columns: 2 3
Enter elements of Matrix A:
1 2 3
4 5 6
Enter elements of Matrix B:
7 8 9
10 11 12
Resulting Matrix (A + B):
8 10 12 
14 16 18

Complexity Analysis

  • Time Complexity: O(rows×cols)
  • Space Complexity: O(rows×cols)

C Program to Add Two Matrices Using Dynamic Memory Allocation

This program demonstrates matrix addition using dynamic memory allocation with malloc() for creating matrices.

#include <stdio.h>
#include <stdlib.h>

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

int main() {
    int rows, cols;

    // Input number of rows and columns
    printf("Enter number of rows and columns: ");
    scanf("%d %d", &rows, &cols);

    // Dynamic memory allocation for matrices
    int **A = (int **)malloc(rows * sizeof(int *));
    int **B = (int **)malloc(rows * sizeof(int *));
    int **result = (int **)malloc(rows * sizeof(int *));
    for (int i = 0; i < rows; i++) {
        A[i] = (int *)malloc(cols * sizeof(int));
        B[i] = (int *)malloc(cols * sizeof(int));
        result[i] = (int *)malloc(cols * sizeof(int));
    }

    // Input elements of first matrix
    printf("Enter elements of Matrix A:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &A[i][j]);
        }
    }

    // Input elements of second matrix
    printf("Enter elements of Matrix B:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &B[i][j]);
        }
    }

    // Call the function to add matrices
    addMatrices(rows, cols, A, B, result);

    // Output the result
    printf("Resulting Matrix (A + B):\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    // Free dynamically allocated memory
    for (int i = 0; i < rows; i++) {
        free(A[i]);
        free(B[i]);
        free(result[i]);
    }
    free(A);
    free(B);
    free(result);

    return 0;
}

Explanation

  • In this program, matrices A, B, and result are dynamically allocated using malloc(). This allows the program to handle matrices of any size, even if the size is not known at compile time.
  • The addMatrices() function is the same as in the previous example, but this time it works with dynamically allocated memory.
  • After the computation, the allocated memory is freed using free() to avoid memory leaks.

Output

Enter number of rows and columns: 2 3
Enter elements of Matrix A:
1 2 3
4 5 6
Enter elements of Matrix B:
7 8 9
10 11 12

Resulting Matrix (A + B):
8 10 12
14 16 18

Complexity Analysis

  • Time Complexity: O(rows×cols)
  • Space Complexity: O(rows×cols)

Conclusion

In conclusion, understanding how to add two matrices in C enhances programming skills and provides insight into more complex mathematical operations. It explores advanced topics such as matrix multiplication and determinants. By mastering matrix addition, programmers can effectively handle multi-dimensional data structures and apply mathematical concepts to real-world problems.

Frequently Asked Questions

1. What basic operations can be performed on matrices in C?

The basic operations include addition, subtraction, multiplication, and finding the transpose of a matrix. Each operation typically involves nested loops to iterate through the elements.

2. Can I use dynamic memory allocation for matrices?

Dynamic memory allocation is commonly used to create matrices of variable sizes. You can allocate memory using malloc and ensure to free it after use to avoid memory leaks:

free(matrix[i]); // Free each row
free(matrix); // Free the main pointer

3. What are the basic operations that can be performed on matrices?

The basic operations include:

  • Addition: Combining two matrices by adding corresponding elements.
  • Subtraction: Similar to addition but involves subtracting corresponding elements.
  • Multiplication: Combining two matrices to produce a third matrix, following specific rules for element multiplication and summation.
  • Transpose: Flipping a matrix over its diagonal, switching the row and column indices.

Read More Articles

Chat with us
Chat with us
Talk to career expert