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

Stack Data Structure, Push, Pop and Peek Operations , Applications of Stack

Stack is a linear data structure. It is collection of ordered data elements. It is also known as LIFO system (last in first out). It means i...