Saturday, August 20, 2011

Program to find Multiplication of two matrices created by using concept of malloc.

//Program to find Multiplication of two matrices created by using concept of malloc.
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
int mul(int **,int,int,int **,int);
void main()
{
 int **a,**b,**c,m,n,p,q,i,j;
 clrscr();
 printf("\n Enter the number of rows in 1st  matrix:");
 scanf("%d",&m);
 printf("\n Enter the number of columns in  1st matrix:");
 scanf("%d",&n);

 printf("\n Enter the number of rows in 2nd  matrix:");
 scanf("%d",&p);
 printf("\n Enter the number of columns in  2nd matrix:");
 scanf("%d",&q);

 a=(int**)malloc(m*sizeof(int*));
 for(i=0;i<m;i++)
 a[i]=(int*)malloc(n*sizeof(int));

 b=(int**)malloc(p*sizeof(int*));
 for(i=0;i<p;i++)
 b[i]=(int*)malloc(q*sizeof(int));

printf("Enter the elements of matrix a");
 for(i=0;i<m;i++)
  for(j=0;j<n;j++)
   scanf("%d",&a[i][j]);

 printf("Enter the elements of matrix b");
 for(i=0;i<p;i++)
  for(j=0;j<q;j++)
   scanf("%d",&b[i][j]);

 if(n==p)
 {
 c=(int**)malloc(m*sizeof(int*));
 for(i=0;i<m;i++)
 c[i]=(int*)malloc(q*sizeof(int));

 c=mul(a,m,n,b,q);
 printf("matrix A:\n");
 for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
   printf(" %d ",a[i][j]);
  printf("\n");
 }
 printf("matrix B:\n");
 for(i=0;i<p;i++)
 {
  for(j=0;j<q;j++)
   printf(" %d ",b[i][j]);
  printf("\n");
 }
  printf("mul of matrix:\n");
 for(i=0;i<m;i++)
 {
  for(j=0;j<q;j++)
   printf(" %d ",c[i][j]);
  printf("\n");
 }
 }
 else
 {
 printf("multiplication not possible");
 }

 getch();
}
int mul(int **a,int m,int n,int **b,int q)
{
int i,j,k;
int **t;
 t=(int**)malloc(m*sizeof(int*));
 for(i=0;i<m;i++)
 t[i]=(int*)malloc(q*sizeof(int));

 for(i=0;i<m;i++)
 {
 for(j=0;j<q;j++)
 {
  t[i][j]=0;
  for(k=0;k<n;k++)
  { t[i][j]+=a[i][k]*b[k][j];}
 }
 }
 return t;
}

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More