How to add two matrices using pointers in c

In this article, we are going to learn how to add two matrices using pointers in C.We will take inputs from users for the two matrix or 2D arrays. Then we will perform the addition on these two matrices element to element.

C proogram to add two matrices using pointers


In this example, we are going to add the elements of matrix 1 to elements of matrix 2. This will be element-to-element addition. The results will be saved in a resultant matrix.

#include <stdio.h>

void AddionOfMatrices(int Matrix1[][3], int Matrix2[][3], int SumMatrix[][3]);


int main()
{
    int Matrix1[3][3];
    int Matrix2[3][3];
    int SumMatrix[3][3];
    int i,j;

    printf("Please enter the elements of First 3x3 2D array (9 elements):\n");

    for(i = 0; i < 3; i++)
    {
        for(j = 0; j < 3; j++)
        {
            scanf("%d", (*(Matrix1 + i) + j));
        }
    }

    printf("Please enter the elements of Second 3x3 2D array (9 elements):\n");

    for(i = 0; i < 3; i++)
    {
        for(j = 0; j < 3; j++)
        {
            scanf("%d", (*(Matrix2 + i) + j));
        }
    }


    AddionOfMatrices(Matrix1, Matrix2, SumMatrix);

    printf("The elements of 3x3 Resultant Matrix are:\n");

    for (i = 0; i < 3; i++)
    {
	printf("Row %d -> ",i);
        for (j = 0; j < 3; j++)
        {
            printf("%d ", *(*(SumMatrix + i) + j));
        }

        printf("\n");
    }
    

    return 0;
}

void AddionOfMatrices(int Matrix1[][3], int Matrix2[][3], int SumMatrix[][3])
{
    int i, j;
 
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            *(*(SumMatrix + i) + j) = *(*(Matrix1 + i) + j) + *(*(Matrix2 + i) + j);
        }
    }
}

Output

Please enter the elements of First 3x3 2D array (9 elements):
1
2
3
4
5
6
7
8
9
Please enter the elements of Second 3x3 2D array (9 elements):
0
9
8
7
6
5
4
3
2
The elements of 3x3 Resultant Matrix are:
Row 0 -> 1 11 11 
Row 1 -> 11 11 11 
Row 2 -> 11 11 11