Addition of Two Matrix Program
Here you will get example code with algorithm to make Addition of Two Matrix program in C.
Matrix addition in C involves adding corresponding elements of two matrices to create a new matrix. It’s done via nested loops that proceed in rows and columns, adding values element by element.
Matrix Addition in C
We will take two matrices as input and displays their sum as output. This program also takes number of rows and columns in matrices as input. In this program variables r and c represents the number of rows and columns respectively.
Array variables x and y represents matrices to be added and z represents the resultant matrix.
For example
The sum of two matrices is given by
z[i][j] = x[i][j] + y[i][j]
in that i and j are row and column(index).
Algorithm for Addition of Two Matrix in C
Step 1: Enter the elements of the first matrix.
Step 2: Enter the elements of the second matrix.
Step 3: Display the elements of the first matrix.
Step 4: Display the elements of the second matrix.
Step 5: Add the elements of the both matrices.
Step 6: Display the sum of the both matrices.
Addition of Two Matrix 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include<stdio.h> main() { int x[5][5],y[5][5],z[5][5],i,j; int r,c; //clrscr(); printf("\nEnter No of Rows & Columns (max : 5,5) :"); scanf("%d%d",&r,&c); printf("\nEnter Elements for 1st Matrix : "); for(i=0;i<r;i++) { for(j=0;j<c;j++) scanf("%d",&x[i][j]); } printf("\nEnter Elements for 2nd Matrix : "); for(i=0;i<r;i++) { for(j=0;j<c;j++) scanf("%d",&y[i][j]); } printf("\nThe Elements In 1st Matrix : \n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("\t%2d ",x[i][j]); printf("\n"); } printf("\nThe Elements In 2nd Matrix : \n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf(" \t%2d ",y[i][j]); printf("\n\n"); } // Addition of Matrix for(i=0;i<r;i++) { for(j=0;j<c;j++) z[i][j]=x[i][j]+y[i][j]; } printf("\nThe Elements After Addition : \n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("\t%2d ",z[i][j]); printf("\n"); } //getch(); return 0; } |
Input
Enter No of Rows & Columns (max : 5,5) :3 3
Enter Elements for 1st Matrix :
1 2 3
2 3 4
3 2 1
Enter Elements for 2nd Matrix :
2 3 4
5 6 3
4 5 6
Output
3 5 7
7 9 7
7 7 7
Check out our other C programming Examples