Write a program to add two matrices/matrix.
Note : Two matrices can only be added if both matrices are of same size.
Note : Two matrices can only be added if both matrices are of same size.
Program to Add Two Matrices/Matrix
#include <stdio.h> main() {
/* Declaring 3*3 matrix. */
int a[3][3]={ {1,2,3}, {2,3,4}, {3,4,5} }; int b[3][3]={ {4,3,1}, {2,5,8}, {3,7,2} }; int c[3][3],i,j; for(i=0;i<3;i++){ for(j=0;j<3;j++){ c[i][j] = a[i][j] + b[i][j]; } } printf("Addition of two matrix is \n"); for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf("%d \t",c[i][j]); } printf("\n"); } } Output Addition of two matrix is 5 5 4 4 8 12 6 11 7
#include <stdio.h> #include <stdlib.h> main() { int a[3][3],b[3][3],c[3][3],row1,row2,col1,col2,i,j; printf("\nEnter the number of Rows for first matrix "); scanf("%d", &row1);
printf("\nEnter the number of column for first matrix "); scanf("%d", &col1); printf("\nEnter the number of Rows for second matrix "); scanf("%d", &row2);
printf("\nEnter the number of Columns for second matrix : "); scanf("%d", &col2); /* Addition of two matrices is only possible
if both matrices are of same size */ if (row1 != row2 || col1 != col2) { printf(" Order is not same "); exit(0); } printf("Enter the Element for first matrix" ); /*Take input for first matrix */
for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { scanf("%d", &a[i][j]); } } printf("Enter the Element for second matrix" ); /* Take input for second matrix. */
for (i = 0; i < row2; i++) { for (j = 0; j < col2; j++) { scanf("%d", &b[i][j]); } } for(i=0;i<row1;i++){ for(j=0;j<col1;j++){ c[i][j] = a[i][j] + b[i][j]; } } printf("Addition of two matrix is \n"); for(i=0;i<row1;i++){ for(j=0;j<col1;j++){ printf("%d \t",c[i][j]); } printf("\n"); } }
No comments:
Post a Comment