C Program to perform Matrix Multiplication

You are Here:

Perform Matrix Multiplication

In the following example, we will multiply the two given matrices (two-dimensional arrays).

Example

C Compiler
#include <stdio.h> int main() { int i, j, k; int arr1[3][3] = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1} }; int arr2[3][3] = { {2, 2, 2}, {2, 2, 2}, {2, 2, 2} }; int arr3[3][3] = {0}; printf("Matrix A (3 x 3):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr1[i][j]); printf("\n"); } printf("\nMatrix B (3 X 3):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr2[i][j]); printf("\n"); } for(i=0; i<3; i++) { for(j=0; j<3; j++) { for(k=0; k<3; k++) arr3[i][j] = arr3[i][j] + arr1[i][k] * arr2[k][j]; } } printf("\nMatrix Multiplication (A x B):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr3[i][j]); printf("\n"); } return 0; }

Output

Matrix A (3 x 3): 1 1 1 1 1 1 1 1 1 Matrix B (3 X 3): 2 2 2 2 2 2 2 2 2 Matrix Multiplication (A x B): 6 6 6 6 6 6 6 6 6

In the following example, we will get the values for (3 x 3) Matrices A and B from the user and display the matrix multiplication.

Example

C Compiler
#include <stdio.h> int main() { int i, j, k; int arr1[3][3], arr2[3][3], arr3[3][3] = {0}; printf("Enter Matrix A (3 x 3):\n"); for(i=0; i<3; i++) for(j=0; j<3; j++) scanf("%d", &arr1[i][j]); printf("\nEnter Matrix B (3 X 3):\n"); for(i=0; i<3; i++) for(j=0; j<3; j++) scanf("%d", &arr2[i][j]); for(i=0; i<3; i++) { for(j=0; j<3; j++) { for(k=0; k<3; k++) arr3[i][j] = arr3[i][j] + arr1[i][k] * arr2[k][j]; } } printf("\nMatrix Multiplication (A x B):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr3[i][j]); printf("\n"); } return 0; }

Output

Enter Matrix A (3 x 3): 2 2 2 2 2 2 2 2 2 Enter Matrix B (3 X 3): 4 4 4 4 4 4 4 4 4 Matrix Multiplication (A x B): 24 24 24 24 24 24 24 24 24

Reminder

Hi Developers, we almost covered 98% of String functions and Interview Question on C with examples for quick and easy learning.

We are working to cover every Single Concept in C.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author