/*write a program on matrix operation using array
coded by KoDes4U.com*/
// list of include files
#include<stdio.h>
#include<conio.h>
#define SIZE 10
//Function definition for reading the matrix
void ReadMatrix(int mat[SIZE][SIZE],int *row,int *col)
{
int i,j;
for(i=0;i<*row;i++)
for(j=0;j<*col;j++)
{
printf("\nEnter the element no:[%d][%]:",i,j);
scanf("%d",&mat[i][j]);
}
}
//Function definition for printing the matrix
void PrintMatrix(int mat[SIZE][SIZE],int row,int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf(" %d",mat[i][j]);
printf("\n\a");
}
}
//Function definition for addition of matrix
int AddMatrix(int mat1[SIZE][SIZE],int mat2[SIZE][SIZE],int mat3[SIZE][SIZE],int row1,int row2,int col1,int col2,int *row3,int *col3)
{
int i,j;
if(row1==row2&&col1==col2) //size should be same
{
for(i=0;i<row1;i++)
for(j=0;j<col1;j++)
mat3[i][j]=mat1[i][j]+mat2[i][j];
*row3=row1;
*col3=col1;
return(1);
}
else
{
printf("\nAddition is no possible");
return(-1);
}
}
//Function of multiplication
int MulMatrix(int mat1[SIZE][SIZE],int mat2[SIZE][SIZE],int mat3[SIZE][SIZE],int row1,int row2,int col1,int col2,int *row3,int *col3)
{
int i,j,k;
if(col1==row2)
{
for(i=0;i<row1;i++)
for(j=0;j<col2;j++)
{
mat3[i][j]=0;
for(k=0;k<col1;k++)
mat3[i][j]=mat3[i][i]+mat1[i][k]*mat2[k][j];
}
*row3=row1;
*col3=col2;
return(1);
}
else
{
printf("\nMultiplication is not possible:");
return(-1);
}
}
//Function definition for transpose of the matrix
void Transpose(int mat1[SIZE][SIZE],int row1,int col1,int mat3[SIZE][SIZE],int *row3,int *col3)
{
int i,j;
for(i=0;i<col1;i++)
{
for(j=0;j<row1;j++)
{
mat3[i][j]=mat1[j][i];
}
}
*row3=col1;
*col3=row1;
}
//Main Function definition
void main()
{
int mat1[SIZE][SIZE],mat2[SIZE][SIZE],mat3[SIZE][SIZE];
int row1,row2,row3,col1,col2,col3;
int choice,val;
clrscr();
printf("\nEnter the rows and columns of 1st matrix:");
scanf("%d %d",&row1,&col1);
printf("\nRead matrix 1");
ReadMatrix(mat1,&row1,&col1);
printf("\nPrint matrix 1");
PrintMatrix(mat1,row1,col1);
printf("\nEnter the rows and columns of 2nd matrix:");
scanf("%d %d",&row2,&col2);
printf("\nRead matrix 2:");
ReadMatrix(mat2,&row2,&col2);
printf("\nprint matrix 2:");
PrintMatrix(mat2,row2,col2);
do
{
printf("\n1)ADD\n2)Multiplication\n3)Transpose\n4)Exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:val=AddMatrix(mat1,mat2,mat3,row1,row2,col1,col2,&row3,&col3);
if(val!=-1)
{
printf("Addition matrix is:");
PrintMatrix(mat3,row3,col3);
}
break;
case 2:val=MulMatrix(mat1,mat2,mat3,row1,row2,col1,col2,&row3,&col3);
if(val!=-1)
{
printf("\nMultiplication of matrices is:");
PrintMatrix(mat3,row3,col3);
}
break;
case 3:Transpose(mat1,row1,col1,mat3,&row3,&col3);
printf("\ntranspose matrix is:");
PrintMatrix(mat3,row3,col3);
break;
case 4:break;
}
}
while(choice!=4);
}
No comments:
Post a Comment