This was a code I wrote back in 2007 as a practice for CS1101C at NUS. Possible improvements: Create a function to print out the matrix & to take in the input for a matrix, so they can be re-used.
/*this prg does matrix multiplication*/
#include<stdio.h>
int main(void)
{
int m1,n1,m2,n2,i,j,k;
float a[100][100],b[100][100],c[100][100];
printf("\n Enter dimensions for A:");
scanf("%i %i",&m1,&n1);
printf("\nEnter the same for B: ");
scanf("%i %i",&m2,&n2);
printf("Enter values for matrix A:\n");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
scanf("%f",&a[i][j]);
// printf("\t");
}
// printf("\n");
}
printf("Enter values for matrix B:\n");
for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
{
scanf("%f",&b[i][j]);
// printf("\t");
}
// printf("\n");
}
for(i=0;i<m1;i++)
for(k=0;k<n2;k++)
for(c[i][k]=0,j=0;j<n1;j++)
c[i][k]+=(a[i][j]*b[j][k]);
printf("The answer C:\n");
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
printf("%.3f \t",c[i][j]);
printf("\n");
}
return 0;
}
/*this prg does matrix multiplication*/
#include<stdio.h>
int main(void)
{
int m1,n1,m2,n2,i,j,k;
float a[100][100],b[100][100],c[100][100];
printf("\n Enter dimensions for A:");
scanf("%i %i",&m1,&n1);
printf("\nEnter the same for B: ");
scanf("%i %i",&m2,&n2);
printf("Enter values for matrix A:\n");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
scanf("%f",&a[i][j]);
// printf("\t");
}
// printf("\n");
}
printf("Enter values for matrix B:\n");
for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
{
scanf("%f",&b[i][j]);
// printf("\t");
}
// printf("\n");
}
for(i=0;i<m1;i++)
for(k=0;k<n2;k++)
for(c[i][k]=0,j=0;j<n1;j++)
c[i][k]+=(a[i][j]*b[j][k]);
printf("The answer C:\n");
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
printf("%.3f \t",c[i][j]);
printf("\n");
}
return 0;
}
No comments:
Post a Comment