A Matrix is Two dimensional array that have number of rows and columns. Addition of Two Matrix in C Programming is very easy.
To write program for adding two matrix is same as we perform matrix addition in mathematics.
To Add Two Numbers rows and columns of both matrix should be same.
Element of each row and column of matrix A will added with same row and column element in matrix B.
The sum of both matrix will produce same row and column matrix in resultant matrix.
Example: Write a program to add two matrix. Firstly, ask from user order of matrix( number of rows and column).
Then take the elements of matrix from user as a input and print the resultant matrix
For example,
if a user input order as 3,3, i.e., three rows and three columns and
First matrix
1 2 3
4 5 6
7 8 9
Second matrix:
9 8 7
6 5 4
3 2 1
then the output of the program (addition of two 3*3 matrix in c) is:
10 10 10
10 10 10
10 10 10
Steps for Addition of Two Matrix in C Programming
- Declare Three matrix f,s and sum.
- Take elements for matrix f and s.
- Add both matrix f and s and save to sum matrix.
- Print the sum matrix.
Matrix addition program in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <stdio.h> int main() { int m, n, i, j, f[10][10], s[10][10], sum[10][10]; printf("Enter the number of rows and columns of matrix\n"); scanf("%d%d", &m, &n); printf("Enter the elements of first matrix\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { scanf("%d", &f[i][j]); } } printf("Enter the elements of second matrix\n"); for (i = 0; i < m; i++) { for (j = 0 ; j < n; j++) { scanf("%d", &s[i][j]); } } printf("Sum of matrices= \n"); for (i = 0; i < m; i++) { for (j = 0 ; j < n; j++) { sum[i][j] = f[i][j] + s[i][j]; printf("%d\t", sum[i][j]); } printf("\n"); } return 0; } |
Number of rows and columns are controlled by variable m and n.
To avoid checking again row and column of both matrix it is accepted at only one place and used by both matrix.
Both Matrix elements are taken from user as per requirement user can also declare matrix elements in program.
OUTPUT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | Enter the number of rows and columns of matrix 3 3 Enter the elements of first matrix 2 3 4 5 6 7 8 9 10 Enter the elements of second matrix 11 12 13 14 15 16 17 18 19 Sum of matrices= 13 15 17 19 21 23 25 27 29 |
Hope you got how to add two matrix in C. Similar way you can also write program to multiply two matrix.