Saturday, August 6, 2011

//Program to show Multiplication,Addition and Subtraction in Matices

#include<stdio.h>
#include<conio.h>
main()
{ int i,j,r1,c1,r2,c2,k,a[30][30],b[30][30],c[30][30];
clrscr();
printf("\n\nEnter the no. of rows and columns for first matrix:\n\n");
scanf("%d%d",&r1,&c1);

printf("\n\nEnter %d elements:\n",r1*c1);
for(i=0 ; i<r1 ; i++)
{ for(j=0 ; j<c1 ; j++)
{ scanf("%d",&a[i][j]);
}
}

printf("\n\nThe first matrix is:\n\n");
for(i=0 ; i<r1 ; i++)
{ for(j=0 ; j<c1 ; j++)
{ printf("%d",a[i][j]);
printf(" ");
}
printf("\n");
}

printf("\n\nEnter the no. of rows and columns for Second matrix:\n\n");
scanf("%d%d",&r2,&c2);

printf("\n\nEnter %d elements:\n",r2*c2);
for(i=0 ; i<r2 ; i++)
{ for(j=0 ; j<c2 ; j++)
{ scanf("%d",&b[i][j]);
}
}javascript:void(0)

printf("\n\nThe Second matrix is:\n\n");
for(i=0 ; i<r2 ; i++)
{ for(j=0 ; j<c2 ; j++)
{ printf("%d",b[i][j]);
printf(" ");
}
printf("\n");
}

if ((r1 == c1) && (r2 == c2))
{ printf("\n\n\nAfter adding 2 matrices the matrix will be:\n");
for(i=0 ; i<r1 ; i++)
{ for(j=0 ; j<c1 ; j++)
{ c[i][j] = a[i][j] + b[i][j];
printf("\n\t%d + %d = %d",a[i][j],b[i][j],c[i][j]);
printf(" ");
}
}
}
else
{ printf("\n\nAddition is not possible");
}


if ((r1 == c1) && (r2 == c2))
{ printf("\n\n\nAfter subtracting 2 matrices the matrix will be:\n");

for(i=0 ; i<r1 ; i++)
{ for(j=0 ; j<c1 ; j++)
{ c[i][j] = a[i][j] - b[i][j];
printf("\n\t%d - %d = %d",a[i][j],b[i][j],c[i][j]);
printf(" ");
}
}
}
else
{ printf("\n\nSubtraction is not possible");
}

if (r2 == c1)
{ printf("\n\n\nAfter multiplying 2 matrices the matrix will be:\n");

for(i=0 ; i<r1 ; i++)
{ printf("\n");
for(j=0 ; j<c2 ; j++)
{ c[i][j] = 0;
for(k=0 ; k<r1 ; k++)
{ c[i][j] = c[i][j] + (a[i][k] * b[k][j]);
}
printf("\t%d ",c[i][j]);
}
printf("\n");
}
}
else
{ printf("\n\nMultiplication is not possible");
}
getch();
}

No comments:

Post a Comment

Programming the Whole World!