Wednesday, July 14, 2010

C programs on array - addition and subtraction of matrices


Addition of two matrices using C Programming Language


#include <stdio.h>
void main()
{
int i, j, k, l, m, n;
float mat1[50][50], mat2[50][50], mat3[50][50];
clrscr();
printf("Program for Addition of matrix.\n\n");
printf("Enter row and column of 1st matrix (1 to 50,1 to 50) : ");
scanf("%d %d", &k, &l);
printf("\nEnter %d elements of 1st matrix\n", k*l);
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
scanf("%f", &mat1[i][j]);
}
printf("Enter row and column of 2nd matrix (1 to 50,1 to 50) : ");
scanf("%d %d", &m, &n);
printf("\nEnter %d elements of 2nd matrix\n", m*n);
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
scanf("%f", &mat2[i][j]);
}
if((k==m)&&(l==n))
{
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
{
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
else
{
printf("\nSummation not possible\n");
}
printf("\n\t*** Matrix 1 ***\n");
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
printf("%8.2f", mat1[i][j]);
printf("\n");
}
printf("\n\t*** Matrix 2 ***\n");
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
printf("%8.2f", mat2[i][j]);
printf("\n");
}
printf("\n\t*** Result ***\n");
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
printf("%8.2f", mat3[i][j]);
printf("\n");
}
getch();
}

Subtraction of two matrices using C Programming Language

 #include <stdio.h>
void main()
{
int i, j, k, l, m, n;
float mat1[50][50], mat2[50][50], mat3[50][50];
clrscr();
printf("Program for subtraction of matrix.\n\n");
printf("Enter row and column of 1st matrix (1 to 50,1 to 50) : ");
scanf("%d %d", &k, &l);
printf("\nEnter %d elements of 1st matrix\n", k*l);
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
scanf("%f", &mat1[i][j]);
}
printf("Enter row and column of 2nd matrix (1 to 50,1 to 50) : ");
scanf("%d %d", &m, &n);
printf("\nEnter %d elements of 2nd matrix\n", m*n);
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
scanf("%f", &mat2[i][j]);
}
if ((k == m) && (l == n))
{
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
mat3[i][j] = mat1[i][j] - mat2[i][j];
}
}
else
{
printf("\nSubtraction not possible\n");
}
printf("\n\t*** Matrix 1 ***\n");
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
printf("%8.2f", mat1[i][j]);
printf("\n");
}
printf("\n\t*** Matrix 2 ***\n");
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
printf("%8.2f", mat2[i][j]);
printf("\n");
}

printf("\n\t*** Result ***\n");
for(i = 0; i < k; i++)
{
for(j = 0; j < l; j++)
printf("%8.2f", mat3[i][j]);
printf("\n");
}
getch();
}


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner