The Wayback Machine - https://web.archive.org/web/20240722044011/https://www.geeksforgeeks.org/c-matrix-addition/
Open In App

Add Matrix in C

Last Updated : 04 Jul, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Matrices are the collection of numbers arranged in order of rows and columns. In this article, we will learn to write a C program for the addition of two matrices.

Addition of two matrices in c

The idea is to use two nested loops to iterate over each element of the matrices. The addition operation is performed by adding the corresponding elements of mat1[] and mat2[] and storing the result in the corresponding position of the resultant matrix.

C Program to Add Two Square Matrices

The below program adds two square matrices of size 4*4, we can change N for different dimensions.

C
// C program to implement
// the above approach
#include <stdio.h>
#define N 4

// This function adds A[][] and B[][],
// and stores the result in C[][]
void add(int A[][N], int B[][N], int C[][N])
{
    int i, j;
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            C[i][j] = A[i][j] + B[i][j];
}

// This function prints the matrix
void printmatrix(int D[][N])
{
    int i, j;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++)
            printf("%d ", D[i][j]);
        printf("\n");
    }
}

// Driver code
int main()
{
    int A[N][N] = { { 1, 1, 1, 1 },
                    { 2, 2, 2, 2 },
                    { 3, 3, 3, 3 },
                    { 4, 4, 4, 4 } };

    int B[N][N] = { { 1, 1, 1, 1 },
                    { 2, 2, 2, 2 },
                    { 3, 3, 3, 3 },
                    { 4, 4, 4, 4 } };

    // To store result
    int C[N][N];
    int i, j;

    printf("Matrix A is \n");
    printmatrix(A);

    printf("Matrix B is \n");
    printmatrix(B);

    add(A, B, C);

    printf("Result matrix is \n");
    printmatrix(C);

    return 0;
}

Output
Matrix A is 
1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 
Matrix B is 
1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 
Result matrix is 
2 2 2 2 
4 4 4 4 
6 6 6 6 
8 8 8 8 

Complexity Analysis

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

C Program to Add Two Rectangular Matrices

Below is the C program to add two rectangular matrices.

C
// C program to implement
// the above approach
#include <stdio.h>
#define M 4
#define N 3

// This function adds A[][] and B[][],
// and stores the result in C[][]
void add(int A[M][N], int B[M][N], int C[M][N])
{
    int i, j;
    for (i = 0; i < M; i++)
        for (j = 0; j < N; j++)
            C[i][j] = A[i][j] + B[i][j];
}

// This function prints the matrix
void printmatrix(int D[M][N])
{
    int i, j;
    for (i = 0; i < M; i++) {
        for (j = 0; j < N; j++)
            printf("%d ", D[i][j]);
        printf("\n");
    }
}

// Driver code
int main()
{
    int A[M][N] = {
        { 1, 1, 1 }, { 2, 2, 2 }, { 3, 3, 3 }, { 4, 4, 4 }
    };

    int B[M][N] = {
        { 2, 1, 1 }, { 1, 2, 2 }, { 2, 3, 3 }, { 3, 4, 4 }
    };

    printf("Matrix A is \n");
    printmatrix(A);

    printf("Matrix B is \n");
    printmatrix(B);

    // To store result
    int C[M][N];
    int i, j;
    add(A, B, C);

    printf("Result matrix is \n");
    printmatrix(C);

    return 0;
}

Output
Matrix A is 
1 1 1 
2 2 2 
3 3 3 
4 4 4 
Matrix B is 
2 1 1 
1 2 2 
2 3 3 
3 4 4 
Result matrix is 
3 2 2 
3 4 4 
5 6 6 
7 8 8 

Complexity Analysis

  • Time Complexity: O(m*n)
  • Auxiliary Space: O(m*n)

Refer to the complete article Program for addition of two matrices for more details!

Related Articles



Similar Reads

Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Move matrix elements in given direction and add elements with same value
Given a matrix m[ ][ ] of size n x n consisting of integers and given a character 'x' indicating the direction. Value of 'x' can be 'u', 'd', 'l', 'r' indicating Up, Down, Left, Right correspondingly. The task is to move the element to given direction such that the consecutive elements having same value are added into single value and shift the res
15+ min read
Add and Remove vertex in Adjacency Matrix representation of Graph
A graph is a presentation of a set of entities where some pairs of entities are linked by a connection. Interconnected entities are represented by points referred to as vertices, and the connections between the vertices are termed as edges. Formally, a graph is a pair of sets (V, E), where V is a collection of vertices, and E is a collection of edg
15+ min read
Add and Remove Edge in Adjacency Matrix representation of a Graph
Prerequisites: Graph and its representationsGiven an adjacency matrix g[][] of a graph consisting of N vertices, the task is to modify the matrix after insertion of all edges[] and removal of edge between vertices (X, Y). In an adjacency matrix, if an edge exists between vertices i and j of the graph, then g[i][j] = 1 and g[j][i] = 1. If no edge ex
13 min read
Program to check diagonal matrix and scalar matrix
Diagonal matrix A square matrix is said to be a diagonal matrix if the elements of the matrix except the main diagonal are zero. A square null matrix is also a diagonal matrix whose main diagonal elements are zero. Examples: Input: Mat[4][4] = {{4, 0, 0, 0}, {0, 5, 0, 0}, {0, 0, 2, 0}, {0, 0, 0, 1}} Output: Yes Input: Mat[4][4] = {{6, 10, 12, 0}, {
10 min read
Check if it is possible to make the given matrix increasing matrix or not
Given a matrix of N X M of positive integers, the task is to find out whether it is possible to make the matrix increasing or not. Print the matrix constructed otherwise print -1. Matrix elements should be greater than zero. A matrix is said to be increasing matrix if: For each row, the elements are in the increasing order.For each column, the elem
10 min read
Program to check if a matrix is Binary matrix or not
Given a matrix, the task is to check if that matrix is a Binary Matrix. A Binary Matrix is a matrix in which all the elements are either 0 or 1. It is also called Logical Matrix, Boolean Matrix, Relation Matrix. Examples: Input: {{1, 0, 1, 1}, {0, 1, 0, 1} {1, 1, 1, 0}} Output: Yes Input: {{1, 0, 1, 1}, {1, 2, 0, 1}, {0, 0, 1, 1}} Output: No Approa
5 min read
Program to convert given Matrix to a Diagonal Matrix
Given a N*N matrix. The task is to convert the matrix to a diagonal matrix. That is to change the values of the non-diagonal elements of a matrix to 0.Diagonal-Matrix: A matrix is called a Diagonal Matrix if all the non-diagonal elements of the matrix are zero.Examples: Input : mat[][] = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }} Output : {{2, 0, 7},
8 min read
Check if matrix can be converted to another matrix by transposing square sub-matrices
Given two N X M matrices of integers. In an operation, we can transpose any square sub-matrix in matrix1. The task is to check if matrix1 can be converted to matrix2 with the given operation.Examples: Input: matrix1[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, matrix2[][] = { {1, 4, 7}, {2, 5, 6}, {3, 8, 9}} Output: Yes Transpose the whole matrix and
10 min read
Practice Tags :
three90RightbarBannerImg