C++ or C program for multiplication of two matrices.

file name:-mulmat.cpp

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#define R1 3
#define C1 2
#define R2 2
#define C2 3
void main(){
int A[R1][C1],B[R2][C2],M[R1][C2],i,j,k;
clrscr();
/*
if(C1==R2){
cout<<"In multiplication of matrices, C1 must be equal to R2"<<endl;
getch();
exit(0);
}
*/
cout<<"Enter elements of matrix A"<<endl;
for(i=0;i<R1;i++){
for(j=0;j<C1;j++){
cout<<"Enter A["<<i<<"]["<<j<<"]= ";
cin>>A[i][j];
}}
cout<<"Enter elements of matrix B"<<endl;
for(i=0;i<R2;i++){
for(j=0;j<C2;j++){
cout<<"Enter B["<<i<<"]["<<j<<"]= ";
cin>>B[i][j];
}}
cout<<"Matrix A ="<<endl;
for(i=0;i<R1;i++){
for(j=0;j<C1;j++){
cout<<A[i][j]<<" ";
}
cout<<endl;
}
cout<<"Matrix B ="<<endl;
for(i=0;i<R2;i++){
for(j=0;j<C2;j++){
cout<<B[i][j]<<" ";
}
cout<<endl;
}
getch();
//Matrix multiplication
for(i=0;i<R1;i++){
for(j=0;j<C2;j++){
M[i][j]=0;
for(k=0;k<C1;k++){
M[i][j]=M[i][j]+A[i][k]*B[k][j];
}}}
cout<<"Multiplication of matrix A and B ="<<endl;
for(i=0;i<R1;i++){
for(j=0;j<C2;j++){
cout<<M[i][j]<<" ";
}
cout<<endl;
}
getch();
}

file name:-mulmat.c

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define R1 3
#define C1 2
#define R2 2
#define C2 3
void main(){
int A[R1][C1],B[R2][C2],M[R1][C2],i,j,k;
clrscr();
/*
if(C1==R2){
printf("in multiplication of matrices,C1 must be equal to R2\n ");
getch();
exit(0);
}
*/
printf("Enter elements of matrix A\n");
for(i=0;i<R1;i++){
for(j=0;j<C1;j++){
printf("enter A[%d][%d]=",i,j);
scanf("%d",&A[i][j]);
}}
printf("enter elements of matrix B\n");
for(i=0;i<R2;i++){
for(j=0;j<C2;j++){
printf("enter B[%d][%d]=",i,j);
scanf("%d",&B[i][j]);
}}
for(i=0;i<R1;i++){
for(j=0;j<C1;j++){
printf ("%d ",A[i][j]);
}
printf("\n");
}
for(i=0;i<R2;i++){
for(j=0;j<C2;j++){
printf ("%d ",B[i][j]);
}
printf("\n");
}
getch();
//matrix multiplication
for(i=0;i<R1;i++){
for(j=0;j<C2;j++){
M[i][j]=0;
for(k=0;k<C1;k++){
M[i][j]=M[i][j]+A[i][k]*B[k][j];
}}}
printf ("multiplication of A and B =\n");
for(i=0;i<R1;i++){
for(j=0;j<C2;j++){
printf ("%.2d ",M[i][j]);
}
printf("\n");
}
getch();
}

No comments:

Post a Comment

Priority Queue

Priority queue:-  It is a special type of queue which stores group of elements. Each element has a priority number associated with it. Prior...