Program to verify the distributive property of matrix multiplication.

#include <stdio.h>
#define MAX 10

void verifydistributive(int A[][MAX], int B[][MAX], int C[][MAX], int a, int b, int c)
{
int abc[MAX][MAX], abac[MAX][MAX];
int i, j, k;
int flag;

/* This loop computes A(B+C) */
for(i=0; i<a; i++)
for(j=0; j<c; j++)
{
abc[i][j]=0;
for(k=0; k<b; k++)
abc[i][j]+=(A[i][k]*(B[k][j]+C[k][j]));
}

/* This loop computes AB */
for(i=0; i<a; i++)
for(j=0; j<c; j++)
{
abac[i][j]=0;
for(k=0; k<b; k++)
abac[i][j]+=(A[i][k]*B[k][j]);
}

/* AC is added to the previous result */
for(i=0; i<a; i++)
for(j=0; j<c; j++)
for(k=0; k<b; k++)
abac[i][j]+=(A[i][k]*C[k][j]);

flag=1;
for(i=0; i<a; i++)
for(j=0; j<c; j++)
if(abc[i][j]!=abac[i][j])
{
flag=0;
break;
}

printf("Now displaying A(B+C):\n");
for(i=0; i<a; i++, printf("\n"))
for(j=0; j<c; j++)
printf("%d ",abc[i][j]);

printf("And AB+AC gave:\n");
for(i=0; i<a; i++, printf("\n"))
for(j=0; j<c; j++)
printf("%d ",abac[i][j]);

if(flag) printf("And thus it has been verified\n");
else printf("Unfortunately, it does not hold\n");
}

int main()
{
int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
int a, b, c;
int i, j;

printf("Enter the order of matrix A: ");
scanf("%d %d",&a,&b);
printf("Enter the number of columns in matrices B and C: ");
scanf("%d",&c);

printf("Now enter the elements of A:\n");
for(i=0; i<a; i++)
for(j=0; j<b; j++)
scanf("%d",&A[i][j]);

printf("Now enter the elements of B:\n");
for(i=0; i<b; i++)
for(j=0; j<c; j++)
scanf("%d",&B[i][j]);

printf("Now enter the elements of C:\n");
for(i=0; i<b; i++)
for(j=0; j<c; j++)
scanf("%d",&C[i][j]);

verifydistributive(A,B,C,a,b,c);

return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s