C Program to Perform Matrix Operation
This is the C program to perform matrix operations such as addition,division and inverse
#include<stdio.h>
int mat1[10][10],mat2[10][10],i,j,k,row1,row2,col1,col2,res[10][10];
char ch;
main()
{
printf("nChoose any Optionn1.Matrix-Additionn2.Matrix-Multiplicationn3.Matrix-Transposen");
scanf("%c",&ch);
switch(ch)
{
case '1':matadd();
break;
case '2':matmul();
break;
case '3':matrans();
break;
default:printf("nInvalid Optionn");
}
}
int readmat(void)
{
if(ch==3)
{
printf("Enter the Rows and Columns of Matrix-1n");
scanf("%d%d",&row1,&col1);
printf("Enter %dx%d Matrix-1 Array Elements n",row1,col1);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("Matrix-1 Accepted Successfullyn");
}
else
{
printf("Enter the Rows and Columns of Matrix-1n");
scanf("%d%d",&row1,&col1);
printf("Enter the Rows and Columns of Matrix-2n");
scanf("%d%d",&row2,&col2);
if((ch==1&&(row1==row2&&col1==col2))||(ch==2&&(col1==row2)))
{
printf("Enter %dx%d Matrix-1 Array Elements n",row1,col1);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("Matrix-1 Accepted Successfullyn");
printf("Enter %dx%d Matrix-2 Array Elements n",row2,col2);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&mat2[i][j]);
}
}
printf("Matrix-2 Accepted Successfullyn");
}
else
{
printf("The Operation Cannot be Performedn");
}
}
}
int displaymat(void)
{
printf("The Resultant Matrix is n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
printf("%d t",res[i][j]);
}
printf("n");
}
}
int preview(void)
{
printf("The Entered Matrices are n");
if(ch==3)
{
printf("Matrix-1:n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
printf("%2d",mat1[i][j]);
}
printf("n");
}
}
else
printf("Matrix-1:n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
printf("%2d",mat1[i][j]);
}
printf("n");
}
printf("Matrix-2:n");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
printf("%2d",mat2[i][j]);
}
printf("n");
}
}
int matadd(void)
{
readmat();
preview();
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
res[i][j]=mat1[i][j]+mat2[i][j];
}
}
displaymat();
}
int matmul(void)
{
readmat();
preview();
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
res[i][j]=0;
for(k=0;k<row2;k++)
{
res[i][j]+=mat1[i][k]*mat2[k][j];
}
}
}
displaymat();
}
int matrans(void)
{
readmat();
preview();
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
res[i][j]=mat1[j][i];
}
}
displaymat();
}
Recent Comments