In this article, we are going to learn how to Multiply two matrices using pointers in C.We will take inputs from users for the two matrix or 2D arrays. Then we will perform the Multiply on these two matrices.
- Write a C program to Multiply two matrix using pointers.
- C proogram to Multiply two matrix using pointers.
C Program to Mutiply two matrix using pointer
In this example, we are going to Multiply the elements of matrix 1 to elements of matrix 2. The results will be saved in a resultant matrix.
#include <stdio.h>
void MultiplyOfMatrices(int Matrix1[][3], int Matrix2[][3], int SumMatrix[][3]);
int main()
{
int Matrix1[3][3];
int Matrix2[3][3];
int MulMatrix[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));
}
}
MultiplyOfMatrices(Matrix1, Matrix2, MulMatrix);
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 ", *(*(MulMatrix + i) + j));
}
printf("\n");
}
return 0;
}
void MultiplyOfMatrices(int Matrix1[][3], int Matrix2[][3], int MulMatrix[][3])
{
int row, col;
int i;
int sum;
for (row = 0; row < 3; row++)
{
for (col = 0; col < 3; col++)
{
sum = 0;
for (i = 0; i < 3; i++)
{
sum += (*(*(Matrix1 + row) + i)) * (*(*(Matrix2 + i) + col));
}
*(*(MulMatrix + row) + col) = sum;
}
}
}
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 -> 26 30 24
Row 1 -> 59 84 69
Row 2 -> 92 138 114