C program to multiply two matrices
In this post, you will learn how to perform matrix multiplication using the C programming language.
Matrix, a set of numbers arranged in rows and columns so as to form a rectangular array. Matrices are utilised substantially more in everyday life than individuals would have suspected. A square matrix can represent a linear transformation of a geometric object. A real-life example is Adobe Photoshop. It uses a matrix to process linear transformations to render images. In robotics and automation, matrices are the fundamental segments for the robot development. The contributions for controlling robots are acquired based on the calculations from matrices.
The different operations on the matrix are also very important for us. Let us discuss how to perform matrix multiplication in the C.
C matrix multiplication using for loop
A nested loop is a loop inside a loop. In the given C program, we have used the nested for loops to iterate through each row and each column and multiply two matrices of 3 rows and 3 columns.
#include<stdio.h>
#include<stdlib.h>
int main(){
int X[10][10],Y[10][10],mul[10][10],row,col,i,j,k;
system("cls");
printf("Enter the number of row: ");
scanf("%d",&row);
printf("Enter the number of column: ");
scanf("%d",&col);
printf("Enter the first matrix element: \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&X[i][j]);
}
}
printf("Enter the second matrix element: \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&Y[i][j]);
}
}
printf("Multiply of the matrix: \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
mul[i][j]=0;
for(k=0;k<col;k++)
{
mul[i][j]+=X[i][k]*Y[k][j];
}
}
}
//for printing result
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
Output of the above code:
Enter the number of row: 3
Enter the number of column: 3
Enter the first matrix element:
3 2 7
1 6 2
7 2 3
Enter the second matrix element:
3 2 8
4 2 6
2 3 6
Multiply of the matrix:
31 31 78
31 20 56
35 27 86
Related Articles
Average of two numbers in CSwapping of two numbers in C using pointers
Armstrong number in C using function
Binary to decimal C program
Sum of array elements in C
Random number generator in C
Factorial program in c using while loop
Student mark sheet program in C
C program to sort names in alphabetical order
C program to find largest number in an array
Print first 10 natural numbers using while loop in C
Simple calculator program in C
C program for simple interest
Swap two numbers without using third variable in C
Radix sort program in C
Bit stuffing program in C
Bubble sort program in C
Decimal to hexadecimal in C
Hexadecimal to decimal in C
Quick sort program in C