Session 7: multiplication of two matrices
Session 7: Write a program in ‘C’ language for the
multiplication of two matrices.
using pointers.
This is the program, which takes two matrices as input and generates multiplication of two matrices as output. In order to multiply the two matrices there is a condition for the two matrices, is given below.
·
The no. of columns of the first
matrix is equal to the no. of rows of the second matrix, then only it is
possible to multiply two matrices, otherwise it is not possible to
multiply two matrices.
Program
#include<stdio.h>
#include<conio.h>
void
input(int **a,int r1, int
c1)
{
int
i,j;
printf("\n enter 1st matrix
elements \n"); if (r1>=10||c1>=10)
{
printf(“\n Unable to enter matrix”); return;
}
else
{
for(i=0;i<r1;i++) for(j=0;j<c1;j++) scanf("%d",&*(*(a+i)+j));
}
}
void
output(int **a, int r2,
int c2)
{
int
i,j;
if
(r1>=10||c1>=10)
{
printf(“\n Unable to enter matrix”); return;
}
else
{
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++) printf("%d\t",*(*(a+i)+j)); printf("\n");
}
}
}
void
multiply(int **a, int **b, int
r1, int c1, int r2, int c2)
{
int
i,j,k,c[10][10]; for(i=0;i<r1;i++)
for(k=0;k<c2;k++)
{
c[i][k]=0;
for(j=0;j<c1;j++)
*(*(c+i)+k)=
*(*(c+i)+k)+ *(*(a+i)+j)* *(*(b+j)+k);
}
printf("\n the multiplication of matrices is \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++) printf("%d\t",*(*(c+i)+j)); printf("\n");
}
}
main()
{
int
r1,c1,r2,c2,**a, **b, **c; clrscr();
printf("\n enter the number
of rows,columns for matrix1\n"); scanf("%d%d",&r1,&c1);
printf("\n enter the number
of rows,columns for matrix2\n");
scanf("%d%d",&r2,&c2);
if(c1!=r2)
{
printf("\n unable to multiply");
return;
}
else
{
input(a,r1,c1);
input(b,r2,c2);
multiply(a,b,r1,c1,r2,c2); output(a,r1,c1);
output(b,r2,c2);
}
getch();
}
Output:
enter the number of rows, columns for matrix1 3
3
enter the number of rows, columns for matrix2 3
3
enter 1st matrix elements 1
2
3
4
5
6
7
8
9
enter 2nd matrix elements 1
1
1
1
1
1
1
1
1
the
first matrix is
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
the
second matrix is
1 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
the multiplication of matrices is
6 | 6 | 6 |
15 | 15 | 15 |
24 | 24 | 24 |
Comments
Post a Comment