Addition of 2 matrix is possible only if both the matrices have same order. Matrices are the 2 Dimensional arrays in C.
That is,
Number of Rows of first matrix = Number of Rows of second matrix and
Number of Columns of first matrix = Number of columns of second matrix.
Example:
a(2, 3) and b(2, 3),
a(3, 5) and b(3, 5),
a(2, 2) and b(2, 2)
NOTE:
If the matrices have different orders they can not be added or subtracted.
2 Dimensional arrays are used to store the matrices.
Now, let us write C program to add 2 matrices using addition() function.
Description:
r – Number of rows of matrix.
c – Number of columns of matrix.
a & b – Matrices to be added which are 2-D arrays.
add – Sum of 2 matrices which is also 2-D array.
addition(r, c, a, b) – Function which adds matrix ‘a’ and ‘b’.
Input : Number of rows and columns, Matrix ‘a’ and ‘b’.
Output : Addition of 2 matrix.
Algorithm to add 2 matrices using Functions:
STEP 2: READ number of rows and columns of matrix
READ r, c
STEP 3: READ the elements of first matrix
LOOP from i = 0 to r
LOOP from j = 0 to c
READ a(i)(j)
STEP 4: READ the elements of second matrix
LOOP from i = 0 to r
LOOP from j = 0 to c
READ b(i)(j)
STEP 5: CALL the addition() function and pass the arguments r, c, a, b
Addition(r, c, a, b)
LOOP from i = 0 to r
LOOP from j = 0 to c
Add corresponding matrix elements and store in ‘add’ matrix
add(i)(j) = a(i)(j) + b(i)(j)
STEP 6: PRINT the addition matrix
LOOP from i = 0 to r
LOOP from j = 0 to c
PRINT add(i)(j)
STEP 7: END
C Program to add 2 matrix using Functions:
#include<conio.h>
void addition(int r,int c,int a[10][10],int b[10][10]);
void main() {
int r, c, a[10][10], b[10][10],i, j;
printf("Enter the number of rows and columns of matrix: ");
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]);
addition(r,c,a,b);
getch();
}
void addition(int r,int c,int a[10][10],int b[10][10])
{
int add[10][10],i,j;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
add[i][j] = a[i][j] + b[i][j];
printf("Addition of two matrices: \n");
for (i = 0; i < r; i++){
for (j = 0; j < c; j++)
printf("%d\t", add[i][j]);
printf("\n");
}
}
Output 1:
Enter the elements of first matrix:
1 2 2
1 2 2
Enter the elements of second matrix:
1 1 1
1 1 1
Addition of two matrices:
2 3 3
2 3 3
Output 2:
Enter the elements of first matrix:
11 0 12
4 3 1
23 9 8
Enter the elements of second matrix:
1 2 8
2 9 8
5 4 3
Addition of two matrices:
12 2 20
6 12 9
28 13 11
QUIZ:
1] Can square matrices of different order be added?
- YES
- NO