- C Programming Examples
- C Programming Examples
- C Print Hello World
- C Get Input from User
- C Print Integer
- C Add Two Numbers
- C Add Subtract Multiply Divide
- C Add n Numbers
- C Area Perimeter of Square
- C Area Perimeter of Rectangle
- C Area Circum of Circle
- C Fahrenheit to Celsius
- C Celsius to Fahrenheit
- C Inches to Centimeters
- C Kilogram to Gram
- C Reverse a Number
- C Swap Two Numbers
- C Interchange Numbers
- C Print ASCII Value
- C Print Fibonacci Series
- C Check Palindrome or Not
- C Check Armstrong or Not
- C Find Armstrong Numbers
- C Find nCr and nPr
- C Find Profit Loss
- C Sum of their Square
- C First & Last Digit Sum
- C Sum of All Digit
- C Product of All Digit
- C Print Total Digit in Number
- C Check Perfect Number
- C Find Basic Gross Salary
- C Round Number to Integer
- C Print Series upto n Term
- C Find Factors of Number
- C if-else & Loop Programs
- C Check Even or Odd
- C Check Prime or Not
- C Check Alphabet or Not
- C Check Vowel or Not
- C Check Leap Year or Not
- C Is Reverse Equal Original
- C Make Calculator
- C Add Digits of Number
- Count Positive Negative Zero
- C Largest of Two Numbers
- C Largest of Three Numbers
- C Smallest of Two Numbers
- C Smallest of Three Numbers
- C Find Factorial of Number
- C Find LCM & HCF
- C Find LCM of n Numbers
- C Find HCF of n Numbers
- C Find Arithmetic Mean
- C Find Average, Percentage
- C Find Student Grade
- C Print Table of Number
- C Print Prime Numbers
- C Find Discount Purchase
- C Calculate Parcel Charge
- C Calculate Wage of Labor
- C Print Phone Bill
- C Conversion programs
- C Decimal to Binary
- C Decimal to Octal
- C Decimal to Hexadecimal
- C Binary to Decimal
- C Binary to Octal
- C Binary to Hexadecimal
- C Octal to Decimal
- C Octal to Binary
- C Octal to Hexadecimal
- C Hexadecimal to Decimal
- C Hexadecimal to Binary
- C Hexadecimal to Octal
- C Pattern Programs
- C Pattern Printing Programs
- C Print Diamond Pattern
- C Print Floyd's Triangle
- C Print Pascal's Triangle
- C Array Programs
- C 1D Array Programs
- C Linear Search
- C Binary Search
- C Largest Element in Array
- C Smallest Element in Array
- C Second Largest/Smallest
- C Count Even Odd
- C Array Element at Even
- C Array Element at Odd
- C Print Even Array Elements
- C Print Odd Array Elements
- C Sum/Product of Even/Odd
- C Reverse an Array
- C Insert Element in Array
- C Delete Element from Array
- C Merge Two Arrays
- C Bubble Sort
- C Selection Sort
- C Insertion Sort
- C Print Common Elements
- C 2D Array Programs
- C Add Two Matrices
- C Subtract Two Matrices
- C Transpose a Matrix
- C Multiply Two Matrices
- C Sum All Matrix Elements
- C Largest Element in Matrix
- C Print Row Column Total
- C 3D Array Programs
- C String Programs
- C Print String
- C Find Length of String
- C Compare Two String
- C Copy a String
- C Concatenate String
- C Reverse a String
- C Count Vowels Consonants
- C Replace Vowel in String
- C Delete Vowels from String
- C Delete Word from String
- C Frequency of Character
- C Count Word in String
- C Remove Spaces from String
- C Sort a String
- C Sort String in Alphabetical
- C Sort Words in Ascending
- C Sort Words in Descending
- C Uppercase to Lowercase
- C Lowercase to Uppercase
- C Swap Two Strings
- C Check Anagram or Not
- C Check Palindrome String
- C Print Number in Words
- C Print Successive Character
- C Character without Space
- C File Programs
- C Read a File
- C Write Content to File
- C Read & Display File
- C Copy a File
- C Merge Two Files
- C Reverse File
- C Count All Character in File
- C List Files in Directory
- C Encrypt & Decrypt a File
- C Delete a File
- C Misc Programs
- Generate Random Numbers
- C Print Date Time
- C Print Message with Time
- C Get IP Address
- C Print Smiling face
- C Pass Array to Function
- Add Two Numbers using Pointer
- C Address of Variable
- C Shutdown Computer
- C Programming Tutorial
- C Tutorial
C Program to Multiply Two Matrices
In this article, you will learn and get code for the multiplication of two matrices in C. However, before proceeding with the program, if you are unfamiliar with how multiplication of two matrices works, I recommend that you review the step-by-step matrix multiplication process There, you can see how a multiplication of two matrices is calculated step by step using a pictorial representation. Now let's move on and implement it in a C program.
Matrix Multiplication in C
To multiply any two matrices in C programming, first ask the user to enter any two matrices, then start multiplying the given two matrices, and store the multiplication result one by one inside any variable, say sum. Store the value of sum in the third matrix (one by one as its element), say mat3, as shown in the program given here.
The question is, "Write a program in C that multiplies two given matrices." The answer to this question is given below. This C program asks the user to enter any two 3*3 matrix elements and multiply them to form a new matrix that is the multiplication result of the two given 3*3 matrices. Here, "3*3 matrix" means a matrix that has 3 rows and 3 columns:
#include<stdio.h> #include<conio.h> int main() { int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k; printf("Enter first 3*3 matrix element: "); for(i=0; i<3; i++) { for(j=0; j<3; j++) scanf("%d", &mat1[i][j]); } printf("Enter second 3*3 matrix element: "); for(i=0; i<3; i++) { for(j=0; j<3; j++) scanf("%d", &mat2[i][j]); } printf("\nMultiplying two matrices..."); for(i=0; i<3; i++) { for(j=0; j<3; j++) { sum=0; for(k=0; k<3; k++) sum = sum + mat1[i][k] * mat2[k][j]; mat3[i][j] = sum; } } printf("\nMultiplication result of the two given Matrix is: \n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d\t", mat3[i][j]); printf("\n"); } getch(); return 0; }
As the above program was written in the Code::Blocks IDE, here is the output you will see on your screen after a successful build and run. This is the first snapshot:
Now, for the first 3*3 matrix, provide any 9 elements, followed by another 9 elements for the second 3*3 matrix. After you've entered all of the 9-9 elements for both the 3*3 matrix, press ENTER to see the multiplication result of the two matrices, as shown in the second screenshot of the sample run below:
Program Explained
- Get the first nine elements, or numbers, from the user and store them inside the first matrix, index-wise, from 00 to 22.
- That is, the first element stored inside mat1[0][0], the second element stored inside mat1[0][1], the third element stored inside mat1[0][2], ... the seventh element stored inside mat1[2][0], the eighth element stored inside mat1[2][1], and the last or ninth element stored inside mat1[2][2].
- In a similar way, get the second set of 9 elements from the user and store it inside the second matrix.
- We now have two 3*3 matrices with 9-9 elements in each.
- Here, we've used three loops to multiply the matrices. The first two are used for row and column, while the third is used to apply the matrix's multiplication rule.
- Apply the matrix multiplication rule to the matrix and multiply it; once the result is obtained, store the value inside the sum variable after multiplying each row element of the first matrix by the corresponding column element of the second matrix, and one by one initialize the value of the sum variable into the third matrix.Never forget to initialize 0 to sum before the multiplying process starts for each index of the third matrix.
- In this way, the third matrix, say mat3, contains a total of 9 elements that will be the multiplication result of the two given matrices, say mat1 and mat2.
- Finally, print the value of the third matrix.
Allow the user to specify the size of the matrix
Now let's modify the above program by implementing an extra feature. That is, this program allows the user to define the size of the matrix.
#include<stdio.h> #include<conio.h> int main() { int mat1[10][10], mat2[10][10], matmult[10][10]; int row1, col1, row2, col2, i, j, k, sum; printf("Enter size of first matrix:\n"); printf("Enter row size: "); scanf("%d", &row1); printf("Enter column size: "); scanf("%d", &col1); printf("\nEnter the element of first matrix:\n"); for(i=0; i<row1; i++) { for(j=0; j<col1; j++) scanf("%d", &mat1[i][j]); } printf("\nEnter size of second matrix:\n"); printf("Enter row size: "); scanf("%d", &row2); printf("Enter column size: "); scanf("%d", &col2); printf("\nEnter the element of second matrix:\n"); for(i=0; i<row2; i++) { for(j=0; j<col2; j++) scanf("%d", &mat2[i][j]); } if(col1!=row2) { printf("\nMultiplication not possible!"); printf("\nExiting...\n"); printf("Press any key..."); getch(); return 0; } printf("\nMultiplying the two matrix...\n"); for(i=0; i<row1; i++) { for(j=0; j<col2; j++) { sum = 0; for(k=0; k<col1; k++) sum = sum + mat1[i][k] * mat2[k][j]; matmult[i][j] = sum; } } printf("The multiplication result (resultant matrix) is:\n"); for(i=0; i<row1; i++) { for(j=0; j<col2; j++) printf("%d ", matmult[i][j]); printf("\n"); } getch(); return 0; }
Before multiplying the two given matrices entered at run-time, we have applied an if statement to check whether the column size of the first matrices is equal to the row size of the second matrices or not.
If it is equal, then start multiplying and find out the result. If it isn't, print something like "Multiplication not possible!" Here is the sample run:
The following is a snapshot after providing row and column sizes as well as matrix elements (for the first matrix):
The snapshot after providing row and column sizes along with matrix elements (for the second matrix). Because we have provided 3 as the row size of the second matrix, which is equal to the column size of the first matrix:
Now let's take another sample run. In this case, let's suppose the user has entered the column size of the first matrix as 3 and the row size of the second matrix as 2, which are not equal:
As you can clearly see from the above sample runs, matrix multiplication is not possible if the column size of the first matrix is not equal to the row size of the second matrix.
The same program in different languages
« Previous Program Next Program »