C Program to Multiply Two Matrices Using Multi-dimensional Arrays
Write a C program to multiply two matrices 2D array in c program
- The program first takes input for two matrices and checks if multiplication is possible.
- Initializes the result matrix with zeros before performing multiplication.
- Uses triple nested loops to perform matrix multiplication by summing products of corresponding elements.
- Displays the final resulting matrix after multiplication.
Example : pgm.c
#include <stdio.h> int main() { int a[10][10], b[10][10], result[10][10]; int r1, c1, r2, c2; // Input size of matrices printf("Enter rows and columns of first matrix: "); scanf("%d %d", &r1, &c1); printf("Enter rows and columns of second matrix: "); scanf("%d %d", &r2, &c2); // Check if multiplication is possible if (c1 != r2) { printf("Matrix multiplication not possible. Columns of first must equal rows of second.\n"); return 0; } // Input elements for first matrix printf("Enter elements of first matrix:\n"); for (int i = 0; i < r1; i++) { for (int j = 0; j < c1; j++) { scanf("%d", &a[i][j]); } } // Input elements for second matrix printf("Enter elements of second matrix:\n"); for (int i = 0; i < r2; i++) { for (int j = 0; j < c2; j++) { scanf("%d", &b[i][j]); } } // Initialize result matrix to 0 for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { result[i][j] = 0; } } // Matrix multiplication logic for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { for (int k = 0; k < c1; k++) { result[i][j] += a[i][k] * b[k][j]; } } } // Display result matrix printf("Resultant Matrix:\n"); for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { printf("%d ", result[i][j]); } printf("\n"); } return 0; }
Output:
Enter rows and columns of first matrix: 2 3
Enter rows and columns of second matrix: 3 2
Enter elements of first matrix:
1 2 3
4 5 6
Enter elements of second matrix:
3 2
4 7
6 8
Resultant Matrix:
29 40
68 91
Enter rows and columns of second matrix: 3 2
Enter elements of first matrix:
1 2 3
4 5 6
Enter elements of second matrix:
3 2
4 7
6 8
Resultant Matrix:
29 40
68 91