Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int main() {
- int n1,m1,n2,m2;
- printf("How many rows will first matrix have?\n");
- scanf("%d", &n1);
- printf("How many columns will first matrix have?\n");
- scanf("%d", &m1);
- printf("How many rows will second matrix have?\n");
- scanf("%d", &n2);
- printf("How many columns will second matrix have?\n");
- scanf("%d", &m2);
- // check the condition to multiply matrices
- if(m1 != n2){
- printf("Bad dimensions.");
- return 0;
- }
- int ar1[n1][m1], ar2[n2][m2], res[n1][m2];
- printf("Provide numbers in the first matrix: \n");
- for(int i = 0; i < n1; ++i){
- for(int j = 0; j < m1; ++j)
- scanf("%d", &ar1[i][j]);
- }
- printf("Provide numbers in the second matrix: \n");
- for(int i = 0; i < n2; ++i){
- for(int j = 0; j < m2; ++j)
- scanf("%d", &ar2[i][j]);
- }
- //initialize whole result array to 0
- for(int i = 0; i < n1; ++i)
- for(int j = 0; j < m2; ++j)
- res[i][j] = 0;
- //multiply first and second matrix and store the value into result array
- for(int i = 0; i < n1; ++i)
- {
- for(int j = 0; j < m2; ++j)
- {
- for(int k=0; k < m1; ++k)
- {
- res[i][j] += ar1[i][k] * ar2[k][j];
- }
- }
- }
- //display the result
- printf("\nFinal matrix: \n");
- for(int i = 0; i < n1; ++i) {
- for (int j = 0; j < m2; ++j) {
- printf("%d", res[i][j]);
- printf("\t");
- }
- printf("\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement