C Online Compiler
Example: Matrix Multiplication Using Functions in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Multiplication Using Functions #include <stdio.h> // Function to get matrix elements from the user void getMatrixElements(int matrix[][10], int rows, int cols, char name) { printf("Enter elements for Matrix %c (%dx%d):\n", name, rows, cols); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { printf("Enter element [%d][%d]: ", i, j); scanf("%d", &matrix[i][j]); } } } // Function to multiply two matrices void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int resultMatrix[][10], int r1, int c1, int r2, int c2) { // Initializing elements of result matrix to 0 for (int i = 0; i < r1; ++i) { for (int j = 0; j < c2; ++j) { resultMatrix[i][j] = 0; } } // Multiplying firstMatrix and secondMatrix and storing it in resultMatrix for (int i = 0; i < r1; ++i) { for (int j = 0; j < c2; ++j) { for (int k = 0; k < c1; ++k) { resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j]; } } } } // Function to display a matrix void displayMatrix(int matrix[][10], int rows, int cols, char name) { printf("\nMatrix %c:\n", name); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { printf("%d\t", matrix[i][j]); } printf("\n"); } } int main() { int firstMatrix[10][10], secondMatrix[10][10], resultMatrix[10][10]; int r1, c1, r2, c2; // Step 1: Get dimensions for the first matrix printf("Enter rows and columns for first matrix: "); scanf("%d %d", &r1, &c1); // Step 2: Get dimensions for the second matrix printf("Enter rows and columns for second matrix: "); scanf("%d %d", &r2, &c2); // Step 3: Validate matrix dimensions for multiplication while (c1 != r2) { printf("Error! Column of first matrix not equal to row of second.\n"); printf("Enter rows and columns for first matrix again: "); scanf("%d %d", &r1, &c1); printf("Enter rows and columns for second matrix again: "); scanf("%d %d", &r2, &c2); } // Step 4: Get elements for the first matrix using a function getMatrixElements(firstMatrix, r1, c1, 'A'); // Step 5: Get elements for the second matrix using a function getMatrixElements(secondMatrix, r2, c2, 'B'); // Step 6: Perform matrix multiplication using a function multiplyMatrices(firstMatrix, secondMatrix, resultMatrix, r1, c1, r2, c2); // Step 7: Display the matrices and the result using a function displayMatrix(firstMatrix, r1, c1, 'A'); displayMatrix(secondMatrix, r2, c2, 'B'); displayMatrix(resultMatrix, r1, c2, 'C'); // Result matrix dimensions are r1 x c2 return 0; }
Output
Clear
ADVERTISEMENTS