C program for matrix multilplication , addition and subtraction


/*Matrix Add,Sub,Multi */
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int n,**p,**q,**r,i,j,k,ch;
printf("enter the order of matrix\n");
scanf("%d",&n);
p=(int**)malloc(n*sizeof(int));
q=(int**)malloc(n*sizeof(int));
r=(int**)malloc(n*sizeof(int));
for(i=0;i<n;i++)
p[i]=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
q[i]=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
r[i]=(int*)malloc(n*sizeof(int));

printf("enter the element of first matrix\n");  //inputing
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&p[i][j]);
printf("enter the element of second matrix");   //inputing
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&q[i][j]);
clrscr();
printf("your entered matrix is\n");     //printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
 printf("  %d",p[i][j]);
}
printf("\n");
}
printf("\n\n");                            //printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
 printf("  %d",q[i][j]);
}
printf("\n");
}
while(1)
{
clrscr();
printf("\n\tEnter 1. for Addtion :");
printf("\n\tEnter 2. for Mult :");
printf("\n\tEnter 3. for Subtract :");
printf("\n\tEnter 4. for Exit :");
printf("\n\tEnter your choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
for(i=0;i<n;i++)   //Add
{
for(j=0;j<n;j++)
{
r[i][j]=p[i][j]+q[i][j];
}
}
printf("\n Addtion matrix is\n");      //output printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf(" %d",r[i][j]);
}
printf("\n");
} getch();
break;
}
case 2:
{
for(i=0;i<n;i++)   //multipicating
{
for(j=0;j<n;j++)
{
r[i][j]=0;
for(k=0;k<n;k++)
{
r[i][j]=r[i][j]+p[i][k]*q[k][j];
}
}
}
printf("\n multiplyed matrix is\n");      //output printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf(" %d",r[i][j]);
}
printf("\n");
}getch();
break;
}
case 3:
{
for(i=0;i<n;i++)   //Add
for(j=0;j<n;j++)
{
r[i][j]=p[i][j]-q[i][j];
}
printf("\n Subtract matrix is\n");      //output printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf(" %d",r[i][j]);
}
printf("\n");
}
}  getch();
break;
case 4 : return;
default : printf("\n\tWrong choice");
}
}
getch();
}

Share on Google Plus

0 comments: