this code is ok but i want to know beforehand if the addition or multiplication is…
- User
this code is ok but i want to know beforehand if the addition or multiplication is possible.
#include<stdio.h> int main() { int m, n, p, q; int matrix1[10][10], matrix2[10][10], sum[10][10], prd[10][10];
printf("Enter the number of columns and rows for the 1st matrix: \n"); scanf("%d %d", &m, &n);
printf("Enter the number of columns and rows for the 2nd matrix: \n"); scanf("%d %d", &p, &q);
printf("Enter the elements of the 1st matrix: \n"); for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { scanf("%d", &matrix1[i][j]); } }
printf("Enter the elements of the 2nd matrix: \n"); for(int i=0; i<p; i++) { for(int j=0; j<q; j++) { scanf("%d", &matrix2[i][j]); } }
printf("\nFirst Matrix is: \n"); for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { printf("%d\t", matrix1[i][j]); } printf("\n"); }
printf("Second Matrix is: \n"); for(int i=0; i<p; i++) { for(int j=0; j<q; j++) { printf("%d\t", matrix2[i][j]); } printf("\n"); }
if(m != p) { printf("Addition of the matrices is not possible\n"); } else { printf("Added Matrix is: \n"); for(int i=0; i<m; i++) { for(int j=0; j<q; j++) { if(i < p && j < n) { sum[i][j] = matrix1[i][j] + matrix2[i][j]; printf("%d\t", sum[i][j]); } else if(i >= p && j >= n) { sum[i][j] = matrix2[i][j]; printf("%d\t", sum[i][j]); } else if(i >= p) { sum[i][j] = matrix1[i][j]; printf("%d\t", sum[i][j]); } else if(j >= n) { sum[i][j] = matrix1[i][j]; printf("%d\t", sum[i][j]); } } printf("\n"); } }
if(n != p) { printf("Multiplication of the matrices is not possible\n"); } else { printf("\nMultiplied Matrix is: \n"); for(int i=0; i<m; i++) { for(int j=0; j<q; j++) { prd[i][j] = 0; for(int k=0; k<n; k++) { prd[i][j] += matrix1[i][k] * matrix2[k][j]; } printf("%d\t", prd[i][j]); } printf("\n"); } }
return 0; }
- Assistant