Example:
If matrix 1:
1 2 3
4 5 6
7 8 9
And matrix 2:
9 8 7
6 5 4
3 2 1
Sum of both matrix =
10 10 10
10 10 10
10 10 10
Required knowledge:
Basic C programming, For loop, Array, MatrixMatrix Addition
Matrix addition is a simple process. Addition of two matrices can be done only and only if both matrices are of same size.Matrix addition is done element wise (entry wise) i.e. Sum of two matrices A and B of size mXn is defined by
(A + B) = Aij + Bij (Where 1 ≤ i ≤ m and 1 ≤ j ≤ n )
Program:
/** * C program to find sum of two matrices of size 3x3 */ #include <stdio.h> int main() { int A[3][3], B[3][3], C[3][3]; int row, col; /* * Reads elements in first matrix */ printf("Enter elements in matrix A of size 3x3: \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { scanf("%d", &A[row][col]); } } /* * Reads elements in second matrix */ printf("\nEnter elements in matrix B of size 3x3: \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { scanf("%d", &B[row][col]); } } /* * Adds both matrices A and B entry wise or element wise * And stores result in matrix C */ for(row=0; row<3; row++) { for(col=0; col<3; col++) { /* Cij = Aij + Bij */ C[row][col] = A[row][col] + B[row][col]; } } /* * Prints the sum of both matrices A and B */ printf("\nSum of matrices A+B = \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { printf("%d ", C[row][col]); } printf("\n"); } return 0; }
Output
Enter elements in matrix A of size 3x3:
1 2 3
4 5 6
7 8 9
Enter elements in matrix B of size 3x3:
9 8 7
6 5 4
3 2 1
Sum of matrices A+B =
10 10 10
10 10 10
10 10 10
1 2 3
4 5 6
7 8 9
Enter elements in matrix B of size 3x3:
9 8 7
6 5 4
3 2 1
Sum of matrices A+B =
10 10 10
10 10 10
10 10 10
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to subtract two matrices.
- C program to multiply two matrices.
- C program to perform Scalar matrix multiplication.
- C program to check whether two matrices are equal or not.
- C program to find transpose of a matrix.
- C program to check Symmetric matrix.
- C program to find sum of all elements of an array.
- C program to find maximum and minimum elements in an array.
- C program to insert an element in an array at specified position.
- C program to delete an element from array at specified position.
- C program to delete all duplicate elements from array.
- C program to print different star(*) pattern series.
- C program to create Simple Calculator using switch case.