C Online Compiler
Example: Matrix Multiplication using Arrays in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Multiplication using Arrays #include <stdio.h> #define MAX_SIZE 10 // Define a maximum size for demonstration purposes int main() { int r1, c1, r2, c2; // Variables for rows and columns of matrix1, matrix2 // Step 1: Get dimensions for the first matrix from the user printf("Enter number of rows for first matrix: "); scanf("%d", &r1); printf("Enter number of columns for first matrix: "); scanf("%d", &c1); // Step 2: Get dimensions for the second matrix from the user printf("Enter number of rows for second matrix: "); scanf("%d", &r2); printf("Enter number of columns for second matrix: "); scanf("%d", &c2); // Step 3: Check for compatibility before multiplication // The number of columns in the first matrix must equal the number of rows in the second matrix. if (c1 != r2) { printf("\nError: Number of columns of the first matrix must be equal to the number of rows of the second matrix.\n"); printf("Matrix multiplication is not possible with these dimensions.\n"); return 1; // Indicate an error } // Declare 2D arrays for matrices and the result int matrix1[MAX_SIZE][MAX_SIZE]; int matrix2[MAX_SIZE][MAX_SIZE]; int result[MAX_SIZE][MAX_SIZE]; // Step 4: Get elements for the first matrix from the user printf("\nEnter elements of the first matrix:\n"); for (int i = 0; i < r1; i++) { for (int j = 0; j < c1; j++) { printf("Enter element matrix1[%d][%d]: ", i, j); scanf("%d", &matrix1[i][j]); } } // Step 5: Get elements for the second matrix from the user printf("\nEnter elements of the second matrix:\n"); for (int i = 0; i < r2; i++) { for (int j = 0; j < c2; j++) { printf("Enter element matrix2[%d][%d]: ", i, j); scanf("%d", &matrix2[i][j]); } } // Step 6: Initialize all elements of the result matrix to zero // This is crucial because we will be accumulating sums into these elements. for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { result[i][j] = 0; } } // Step 7: Perform matrix multiplication // The core logic involves three nested loops: // Outer loop (i): Iterates through rows of the first matrix (and result matrix). // Middle loop (j): Iterates through columns of the second matrix (and result matrix). // Inner loop (k): Iterates through columns of the first matrix (which must match rows of the second matrix). // This loop calculates each element result[i][j] by summing products. for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { for (int k = 0; k < c1; k++) { // Or k < r2, since c1 == r2 result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } // Step 8: Display the resultant matrix printf("\nResultant Matrix:\n"); for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { printf("%d\t", result[i][j]); // Print element followed by a tab } printf("\n"); // Move to the next line after printing a row } return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS