C Online Compiler
Example: 2x2 Matrix Multiplication in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// 2x2 Matrix Multiplication #include <stdio.h> int main() { int a[2][2], b[2][2], c[2][2], i, j, k; // Step 1: Get elements of the first matrix printf("Enter elements of 2x2 Matrix A:\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("Enter A[%d][%d]: ", i, j); scanf("%d", &a[i][j]); } } // Step 2: Get elements of the second matrix printf("\nEnter elements of 2x2 Matrix B:\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("Enter B[%d][%d]: ", i, j); scanf("%d", &b[i][j]); } } // Step 3: Initialize the result matrix C with zeros for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { c[i][j] = 0; } } // Step 4: Perform matrix multiplication // The outer two loops iterate through rows (i) and columns (j) of the result matrix C. // The innermost loop (k) performs the dot product of A's row i and B's column j. for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { for (k = 0; k < 2; k++) { c[i][j] += a[i][k] * b[k][j]; } } } // Step 5: Display the resultant matrix printf("\nResultant Matrix C (A * B):\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("%d\t", c[i][j]); } printf("\n"); // New line after each row } return 0; }
Output
Clear
ADVERTISEMENTS