Subscribe

RSS Feed (xml)

Tuesday, January 6, 2009

Write a C program to calculate the Addition of two matrices.

#include(stdio.h) // place this '<' & '>' instead of '(' & ')' before stdio.h
#include(conio.h)
int main(void)
{
int a[5][5], b[5][5], sum[5][5];
int r1, c1, r2, c2, i, j;
clrscr( );
printf(" Enter the 1st matrix rows and columns: ");
scanf(" %d %d", &r1, &c1);
printf("\n Enter the 2nd matrix rows and columns:");
scanf(" %d %d", &r2, &c2);
if(r1==r2 && c1==c2)
{
printf("\n Enter the 1st matrix elements:" );
for(i=0; i < r1 ; i++)
for(j=0; j < c1; j++)
scanf("%d", &a[i ][ j]);
printf("\n Enter the 2nd matrix elements:" );
for(i=0; i < r2 ; i++)
for(j=0; j < c2; j++)
scanf("%d", &b[i ][ j]);
// Operation Part
for(i=0; i < r1; i++)
{
for(j=0; j < c1; j++)
{
sum[i][ j]=a[i][ j]+b[i][ j];
} }
printf("\n Addition Matrix: ");
for(i=0; i < r1; i++)
{
printf("\n");
for(j=0; j < c1; j++)
printf("%3d", sum[i][ j]); // %3d means 3 digit space betw every number
} } //if closed
else
printf("\nMatrix Addition is not possible.");
getch( );
return 0;
}

Note:- Here variable 'r1, r2' are rows and 'c1,c2' are columns.

No comments:

Post a Comment