11. write a C program that uses functions to perform addition and multiplication of two matrices


 Program that uses functions to perform following :

a) Addition of two matrices

Source Code:

#include<stdio.h>
int main()
{
int A[5][5],B[5][5],C[5][5],r,c;
printf("Enter rows and columns:");
scanf("%d%d",&r,&c);
printf("\n Enter the elements of matrix A:\n");
for(int i=0;i<r;++i)
{
for(int j=0;j<c;++j)
{
printf("Enter values of elements of A[%d][%d]:",i,j);
scanf("%d",&A[i][j]);
}
}
printf("\nEnter the elements of matrix B:");
for(int i=0;i<r;++i)
{
for(int j=0;j<c;++j)
{
printf("\n Enter values of elements in B[%d][%d]:",i,j);
scanf("%d",&B[i][j]);
}
}
printf("\n Addition of A and B:\n");
for(int i=0;i<r;++i)
{
for(int j=0;j<c;++j)
{
C[i][j]=A[i][j]+B[i][j];
printf(" %d \t",C[i][j]);
}
printf("\n");
}
return 0;
}

Output:

Enter rows and columns:2
2
Enter the elements of matrix A:
Enter values of elements of A[0][0]:1
Enter values of elements of A[0][1]:0
Enter values of elements of A[1][0]:2
Enter values of elements of A[1][1]:8
Enter the elements of matrix B:
 Enter values of elements in B[0][0]:1
 Enter values of elements in B[0][1]:0
 Enter values of elements in B[1][0]:9
 Enter values of elements in B[1][1]:1
 Addition of A and B:
 2     0   
 11     9 
   

b) Multiplication of two matrices

Source Code:

#include <stdio.h>
int main()
{
int a[3][3],b[3][3],c[3][3],r1,c1,r2,c2,sum=0,i,j,k;
printf("Enter  no.Rows and Columns for matrix A:\n");
scanf("%d%d",&r1,&c1);
printf("Enter  no.Rows and Columns for matrix B:\n");
scanf("%d%d",&r2,&c2);
if(c1==r2)
{
printf("Enter matrix A elements:\n");
for (i=0; i<r1; i++)
{
for (j=0; j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter matrix B elements:\n");
for (i=0; i<r2; i++)
{
for (j=0; j<c2;j++)
scanf("%d",&b[i][j]);
}
for (i=0; i<r1; i++)
{
for (j=0;j<c2;j++)
{
sum=0;
for (k=0; k<c1; j++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}
}
printf("\n multiplication result of two given matrices:");
for (i= 0; i< r1; i++)
{
for (j=0; j< c2; j++)
printf("%d\t",c[i][j]);
printf("\n");
}
}
else
{
printf("\n Matrix multiplication is not possible\n");
}
return 0;
}

Output:

Enter  no.Rows and Columns for matrix A:
2
3
Enter  no.Rows and Columns for matrix A:
3
2
Enter matrix A elements:
2  
-3
4
53
3
5
Enter matrix B elements:
3
3
5
0
-3
4

multiplication result of two given matrices:
-21  22
159  179

No comments:

Post a Comment