Sunday, November 28, 2010

Write a C program to add two matrices & store the results in the 3rd matrix

#include

#include

int main()

{



int p,q;

printf("Enter the order of the matrix Ex:- 2 2 or 3 3\n");

GO:// Goto lable to prompt correct order

scanf("%d%d",&p,&q);



int m = p, n = q;

int a[m][n],b[m][n],c[m][n],i,j,k=0;

if ( m == p && n == q) // checking size

{

printf("Matrix can be added\n");



printf("Enter the Elements to Matrix A\n");

for(i=0;i < m;i++)

{

for(j=0;j < n;j++)

{

printf("A(%d, %d) = ",i,j);

scanf("%d",&a[i][j]);

}

printf("\n");

}

//////////////////////////Add Elements in Array a//////////////////////////////////



printf("Enter the Elements to Matrix B\n");

for(i=0;i < p;i++)

{

for(j=0;j < q;j++)

{

printf("B(%d, %d) = ",i,j);

scanf("%d",&b[i][j]);

}

printf("\n");

}

///////////////////////////Add Elements in Array b/////////////////////////////////





for(i=0;i < m;i++)

for(j=0;j < n;j++)

{

//printf("%d + %d = %d\n",a[i][j],b[i][j],a[i][j]+b[i][j]);

c[i][j]=a[i][j]+b[i][j];

//printf("Sum = %d \n",c[i][j]);



}

///////////////////////////Sum array a and array b into array c/////////////////////////////////

printf("\tSum of two Martices\n\n");

for(i=0;i < m;i++)

{

for(j=0;j < n;j++)

printf("%d\t",c[i][j]);

printf("\n");

}





///////////////////////////Multiplication array a and array b into array c/////////////////////////////////

for(i=0;i < m;i++)

for(j=0;j < n;c[i][j++] = 0);

printf("\nMultiplication of two Martices\n\n");



for(i=0;i < m;i++)

{

for(j=0;j < n;j++)

for(k=0;k < n;k++)

c[i][j] += a[i][k] * b[k][j];

}



for(i=0;i < m;i++)

{

for(j=0;j < n;j++)

printf("%d\t",c[i][j]);

printf("\n\n");

}





}

else

{

printf("Re-Enter correct Order\n");

goto GO;



}

getch();

}