1 C-Add, Sum, Mul
1 C-Add, Sum, Mul
Aim:
Write the C program to perform Addition, Subtraction and Multiplication o f two matrices.
Algorithm:
1. Start
2. Input the number of rows (r) and columns (c) for the matrices
3. Initialize two matrices, A and B, with dimensions r x c
4. Input elements for matrix A
5. Input elements for matrix B
6. Print matrices A and B
7. Ask user for choice (addition or subtraction or multiplication)
8. Perform chosen operation:
- Addition: add corresponding elements of A and B
- Subtraction: subtract corresponding elements of B from A
- Multiplication: multiply corresponding elements of A and B
9. Print resultant matrix
10. Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],sum[10][10],dif[10][10],mul[10][10], r, c,i,j,k;
printf("Enter the number of rows and columns of matrix:\n");
scanf("%d %d",&r,&c);
printf("Enter the elements of first matrix: \n");
for(i=0;i<r;i++)
for(j = 0;j<c;j++)
scanf("%d",&a[i][j]);
printf("Enter the elements of second matrix: \n");
for(i=0;i<r;i++)
for(j = 0;j<c;j++)
scanf("%d",&b[i][j]);
printf("The addition of two matrices is: \n");
for(i=0;i<r;i++)
for(j = 0;j<c;j++)
sum[i][j]=a[i][j] + b[i][j];
for(i=0;i<r;i++)
{
for(j = 0;j < c;j++)
printf(" %d \t ",sum[i][j]);
printf("\n");
}
printf("The subtraction of two matrices is: \n");
for(i=0;i<r;i++)
for(j = 0;j<c;j++)
dif[i][j]=a[i][j] - b[i][j];
for(i=0;i<r;i++)
{
for(j = 0;j < c;j++)
printf(" %d \t ",dif[i][j]);
printf("\n");
}
printf("The multiply of two matrices is: \n");
for(i=0;i<r;i++)
{
for(j = 0;j<c;j++)
{
mul[i][j]=0;
for(k = 0;k<c;k++)
{
mul[i][j]+=a[i][k] *b[k][j];
}
}
}
for(i=0;i<r;i++)
{
for(j = 0;j < c;j++)
printf(" %d \t ",mul[i][j]);
printf("\n");
}
getch();
clrscr();
}
Output 1:
Output 2: