Multiplication of Two Matrices in C Program
Program Description:
We have looked at the Matrix Transpose Program in earlier articles, In today’s article, We will look at the Multiplication of Two Matrices in C program. The program should accept two Matrices from the user and perform the multiplication/dot product of the matrices and provide the output.
Before going to look at the program. Let’s see how to multiply two matrices (dot product of two matrices)
Multiplication of Two Matrices:
Let’s say we have two matrices X and Y.
The dimensions of the first matrix X is m x n. i.e the number of rows in the X is equal to m and the number of columns in the X are n.
The dimensions of the second matrix Y is n x q. i.e the number of rows in the matrix Y is equal to n and the number of columns are q.
The two matrices can be multiplicable only if the number of columns in the first Matrix(X) is equal to the number of rows in the second matrix.
In the above example, The X matrix has dimensions as m x n and Y Matrix has dimensions as n x q. So the Matrices X and Y satisfy the condition and we can multiply the Matrix X and Matrix Y. The multiplication of the Matrix X and Matrix Y generates a new matrix called Matrix Z ( Z = X * Y). The matrix Z will have dimensions as m x q.
Let’s look at an example to understand the matrix multiplication operation.
Matrix – X: ( 2X2 )
1 2 |
4 6 2 8 |
Matrix – Y: ( 2X2 )
1 2 |
8 3 5 7 |
Multiplication of Two Matrices X and Y is ( X * Y) :
1 2 |
62 54 56 62 |
Please look at the following graphical explanation.
As we can see from the above image, In order to calculate an element in Matrix Z (Output Matrix), We need to calculate the product of the corresponding row in Matrix X and the corresponding column in Matrix Y.
For Example, To Calculate the First Element in Matrix Z, We need to multiply the elements of First Row in the Matrix X and the First Column in Matrix Y then add them to create the Z[0][0] element.
Z[0][0] = (4*8)+(6*5)
Similarly, We need to calculate the other elements of the output matrix (i.e Matrix Z).
Let’s look at a C Program to better understand the matrix multiplication operation.
Prerequisites:
It is recommended to know the basics of the Arrays and Multi-dimensional arrays in C Langauge. Please go through the following articles to learn more about them
- Introduction to C Arrays – How to Declare, Access, and Modify Arrays
- How to pass arrays to functions in C
- Functions in C Language
- 2D arrays in C with Example programs
Multiplication of Two Matrices in C Program Explanation:
Let’s look at the step-by-step explanation of the Matrix multiplication program in C programming language.
- Create two Macros named ROWS and COLUMNS, Which holds the max number of rows and columns (Please change this number if you want to play with the large arrays)
- Start the Program by declaring three Matrices (2D Arrays). They are X matrix, Y matrix, and Z Matrix. The row size and column size of the matrices are ROWS and COLUMNS respectively.
- Prompt the user to provide the desired Row size and Column Size for First Matrix i.e X, and store them in the variables rows1 and columns1 respectively. (Note, These rows and columns are small letters – C is Case Sensitive language)
- Check for array bounds using the (rows1 >= ROWS || rows1 <= 0 || columns1 >= COLUMNS || columns1 <= 0) condition, And display an error message if the row1/column1 sizeis beyond the present limits.
- Repeat the Step-3 and Step-4 for Second Matrix-Y
- Check if We can multiply Matrices X and Y with given column and row sizes using the (columns1 != rows2) condition and display an error message if we can’t multiply the matrices.
- Take the user input for Matrix-X, We need to create two For Loops, One For Loop will iterate over the rows, and the Second For Loop will iterate over the columns
- Create the First For Loop ( Outer Loop), Start the iteration from i=0 and go till the i<rows (Loop syntax for(i=0; i<rows; i++) ). At Each iteration of the Outer Loop,
- Create the second For Loop ( Inner Loop). This loop is a Nested loop that will be inside the Outer Loop. Start the Loop from j=0 and go till the j<columns (i.e for(j=0; j<columns; j++) ). At each iteration of the Inner Loop
- Prompt the user to provide the Matrix or 2D Array element and Read the element using the scanf function and Update the X[i][j] element.
- Repeat the above step for all elements in the 2D array or matrix
- Create the second For Loop ( Inner Loop). This loop is a Nested loop that will be inside the Outer Loop. Start the Loop from j=0 and go till the j<columns (i.e for(j=0; j<columns; j++) ). At each iteration of the Inner Loop
- Repeat the Step 8 to Take the Second Matrix ( Matrix-Y) elements from the user.
- To Calculate the Multiplication of Two Matrices in C, We need to go through the all elements of the matrices using the loops
- Create For Loop to iterates over rows – for(i=0; i<rows; i++)
- Create another For loop to iterates over columns – for(j=0; j<columns; j++)
- Now we need to multiply the ith row with the j column
- Create another loop, Which goes from k=0 till the k<column1
- Perform the Z[i][j] += X[i][k] * Y[k][j]; operation.
- Create another For loop to iterates over columns – for(j=0; j<columns; j++)
- Once the above <b>Step 11</b> is finished, The Matrix-Z contains the Multiplication result of Matrix-X and Matrix-Y.
- Display the Results( Maxtrix-Z) using loops and printf function.
- Stop the Program.
📢 This program is part of the Series of Array & Matrix Practice Programs
Program to Calculate Multiplication of Two Matrix in C Using Loops:
Here is the Program to Perform the Multiplication of Two Matrices or Dot Product of the two matrices in C language.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
/* Program to Multiplication Two Matrices in C SillyCodes.com */ #include <stdio.h> #define ROWS 100 #define COLUMNS 100 int main() { // Declare three matrices. // 'X' & 'Y' are Input matrices // 'Z' stores result of 'X' and 'Y' matrices mutliplication int X[ROWS][COLUMNS], Y[ROWS][COLUMNS], Z[ROWS][COLUMNS] = {0}; int rows1, columns1, rows2, columns2, i, j; // Take the Row size and Column size from user // Row and Column size for first Matrix printf("Enter the Row size for First Matrix(1-%d): ", ROWS); scanf("%d", &rows1); printf("Enter the Column Size for First Matrix(1-%d): ", COLUMNS); scanf("%d", &columns1); // check for array bounds for First Matrix if(rows1 >= ROWS || rows1 <= 0 || columns1 >= COLUMNS || columns1 <= 0) { printf("Invalid Rows or Columns size, Please Try again \n"); return 0; } // Take row and column size for the second matrix printf("Enter the Row size for Second Matrix(1-%d): ", ROWS); scanf("%d", &rows2); printf("Enter the Column Size for Second Matrix(1-%d): ", COLUMNS); scanf("%d", &columns2); // check for array bounds for Second Matrix if(rows2 >= ROWS || rows2 <= 0 || columns2 >= COLUMNS || columns2 <= 0) { printf("Invalid Rows or Columns size, Please Try again \n"); return 0; } // Check if we can mutliply the Matrices if(columns1 != rows2) { printf("ERROR: Can't Multiply Matrices, Please try again\n"); return 0; } // Take the user input for 1st Matrix - 'X' printf("Enter Elements for the First Matrix(X) of Size %dX%d: \n", rows1, columns1); for(i=0; i<rows1; i++) { for(j=0; j<columns1; j++) { // printf("X[%d][%d]: ", i, j); scanf("%d", &X[i][j]); } } // Take the user input for 2nd Matrix - 'Y' printf("Enter Elements for the Second Matrix(Y) of Size %dX%d: \n", rows2, columns2); for(i=0; i<rows2; i++) { for(j=0; j<columns2; j++) { // printf("Y[%d][%d]: ", i, j); scanf("%d", &Y[i][j]); } } // Multiply two Matrices for (int i = 0; i < rows1; i++) { for (int j = 0; j < columns2; j++) { // mutliply the i'th row with j'th column for (int k = 0; k < columns1; k++) { Z[i][j] += X[i][k] * Y[k][j]; } } } // Print the Result printf("Mutliplication of Two Matrices (Z = X*Y) is : \n"); for(i=0; i<rows1; i++) { for(j=0; j<columns2; j++) { // Print Elements printf("%d ", Z[i][j]); } printf("\n"); } return 0; } |
Program Output:
Compile the program.
$ gcc mul-two-matrices.c
Run the Program.
Test Case 1: When the First Matrix and Second Matrix have the same row and column size.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$ ./a.out Enter the Row size for First Matrix(1-100): 2 Enter the Column Size for First Matrix(1-100): 2 Enter the Row size for Second Matrix(1-100): 2 Enter the Column Size for Second Matrix(1-100): 2 Enter Elements for the First Matrix(X) of Size 2X2: 4 6 2 8 Enter Elements for the Second Matrix(Y) of Size 2X2: 8 3 5 7 Mutliplication of Two Matrices (Z = X*Y) is : 62 54 56 62 $ |
Test Case 2: When the First Matrix and Second Matrix has different row and columns Size
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$ ./a.out Enter the Row size for First Matrix(1-100): 2 Enter the Column Size for First Matrix(1-100): 3 Enter the Row size for Second Matrix(1-100): 3 Enter the Column Size for Second Matrix(1-100): 2 Enter Elements for the First Matrix(X) of Size 2X3: 1 2 3 4 5 6 Enter Elements for the Second Matrix(Y) of Size 3X2: 7 8 9 10 11 12 Mutliplication of Two Matrices (Z = X*Y) is : 58 64 139 154 $ |
As we can see from the above output, The program is properly calculating the multiplication of two matrix and generating the output.
Test Case 3: Negative tests: When the matrices are not suited for matrix multiplication.
1 2 3 4 5 6 7 8 |
// Negative Test case $ ./a.out Enter the Row size for First Matrix(1-100): 4 Enter the Column Size for First Matrix(1-100): 3 Enter the Row size for Second Matrix(1-100): 2 Enter the Column Size for Second Matrix(1-100): 4 ERROR: Can't Multiply Matrices, Please try again $ |
The first matrix column size must be equal to the second matrix row size for the matrix multiplication to work. In the above example, The column1 and row2 are not matching. So we can’t multiply the matrices. So the program displayed the error message – ERROR: Can't Multiply Matrices, Please try again
Multiplication of Two Matrices using Functions in C Programming Language:
Let’s look at the matrix multiplication program using functions in the C language. It is always recommended to divide the programs into smaller sub-functions, where each function does a specific task. So in the above program, We have written all the code in the single function i.e main() function, So let’s divide the above program to use the functions for reading user input, displaying results, and calculating the multiplication.
Here is the rewritten version of the above matrix multiplication program. Where we used three user-defined functions(except main() function).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
/* Program to Multiply Two Matrices in C using functions SillyCodes.com */ #include <stdio.h> // Create Macros to store MAX Row and Column Size #define ROWS 100 #define COLUMNS 100 // Function declaration void multiplyMatrices(int rows1, int columns1, int rows2, int columns2, int X[rows1][columns1], int Y[rows2][columns2], int Z[rows1][columns2]); /** * @brief - Read Matrix from the user and update 'A' * * @param rows - Rows in Matrix(2Darray) * @param columns - Columns in 'A' * @param A - 'A' is Matrix or 2D array */ void readMatrix(int rows, int columns, int A[rows][columns]) { int i, j; for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { //printf("A[%d][%d]: ", i, j); scanf("%d", &A[i][j]); } } } /** * @brief - Print the elements of the Matrix * * @param rows - Rows in Matrix(2Darray) * @param columns - Columns in 'A' * @param A[][] - 'A' is a Matrix or 2D array */ void displayMatrix(int rows, int columns, int A[rows][columns]) { int i, j; for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { // Print Elements printf("%d ", A[i][j]); } printf("\n"); } } int main() { // Declare three matrices. // 'X' & 'Y' are Input matrices // 'Z' stores result of 'X' and 'Y' matrices mutliplication int X[ROWS][COLUMNS], Y[ROWS][COLUMNS], Z[ROWS][COLUMNS] = {0}; int rows1, columns1, rows2, columns2, i, j; // Take the Row size and Column size from user // Row and Column size for first Matrix printf("Enter the Row size for First Matrix(1-%d): ", ROWS); scanf("%d", &rows1); printf("Enter the Column Size for First Matrix(1-%d): ", COLUMNS); scanf("%d", &columns1); // check for array bounds for First Matrix if(rows1 >= ROWS || rows1 <= 0 || columns1 >= COLUMNS || columns1 <= 0) { printf("Invalid Rows or Columns size, Please Try again \n"); return 0; } // Take row and column size for the second matrix printf("Enter the Row size for Second Matrix(1-%d): ", ROWS); scanf("%d", &rows2); printf("Enter the Column Size for Second Matrix(1-%d): ", COLUMNS); scanf("%d", &columns2); // check for array bounds for Second Matrix if(rows2 >= ROWS || rows2 <= 0 || columns2 >= COLUMNS || columns2 <= 0) { printf("Invalid Rows or Columns size, Please Try again \n"); return 0; } // Check if we can mutliply the Matrices if(columns1 != rows2) { printf("ERROR: Can't Multiply Matrices, Please try again\n"); return 0; } // Take the user input for 1st Matrix - 'X' printf("Enter Elements for the First Matrix(X) of Size %dX%d: \n", rows1, columns1); readMatrix(rows1, columns1, X); // Take the user input for 2nd Matrix - 'Y' printf("Enter Elements for the Second Matrix(Y) of Size %dX%d: \n", rows2, columns2); readMatrix(rows2, columns2, Y); // Multiply two matrices 'X'*'Y' element by element multiplyMatrices(rows1, columns1, rows2, columns2, X, Y, Z); // Print the Result printf("Mutliplication of Two Matrices (Z=X*Y) is : \n"); displayMatrix(rows1, columns2, Z); return 0; } /** * @brief - Multiply Matrices pointed by 'X' and 'Y' and Store the result in 'Z' * * @param rows1 - Matrix-1 Rows * @param columns1 - Matrix-1 Columns * @param row2 - Matrix-2 Rows * @param column2 - Matrix-2 Columns * @param X - Matrix-1 * @param Y - Matrix-2 * @param Z - Result of X*Y */ void multiplyMatrices(int rows1, int columns1, int rows2, int columns2, int X[rows1][columns1], int Y[rows2][columns2], int Z[rows1][columns2]) { int i, j; // Multiply two Matrices for (int i = 0; i < rows1; i++) { for (int j = 0; j < columns2; j++) { // mutliply the i'th row with j'th column for (int k = 0; k < columns1; k++) { Z[i][j] += X[i][k] * Y[k][j]; } } } } |
The functions are
- The
readMatrix() function – Used to read the matrix elements from the user and update the given matrix
- Function Prototype – void readMatrix(int rows, int columns, int A[rows][columns])
- The readMatrix() function takes three formal arguments which are rows, columns, and Matrix A.
- This function uses Two For loops to iterate over the given matrix A and updates its elements by using the scanf function – scanf(“%d”, &A[i][j]);
- The readMatrix() function doesn’t return anything back to the caller. So return type is void.
- As the arrays are passed by the address/reference, All the changes made to the Matrix-A in the readMatrix() function will be visible in the Caller Function (i.e main() function).
- The
displayMatrix() function is used to print the Matrix elements on the Standard Output.
- The prototype of displayMatrix function is void displayMatrix(int rows, int columns, int A[rows][columns])
- Similar to the readMatrix() function, The displayMatrix() function also takes three formal arguments. i.e rows, columns, and A[][] (2D Array)
- The displayMatrix() function uses Two For loops to iterate over the A matrix and print the elements of the matrix. – printf("%d ", A[i][j]);
- The
multiplyMatrices() function – This function performs the multiplication operation of the
Matrix-X and
Matrix-Y
- Function Prototype – void multiplyMatrices(int rows1, int columns1, int rows2, int columns2, int X[rows1][columns1], int Y[rows2][columns2], int Z[rows1][columns2]);
- This function takes Seven Formal Arguments which are rows1, columns1, rows2, columns2, matrix X, matrix Y, and matrix Z.
- The multiplyMatrices() function uses loops to iterate over the elements of the Matrices X and Y and Performs the dot product of the corresponding row in Matrix X and the corresponding column in Matrix Y. Finally, stores the results in the Matrix-Z – Z[i][j] += X[i][k] * Y[k][j];
Program Output:
Let’s compile and run the program.
Test 1: Normal cases:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
$ gcc mul-two-matrices-func.c $ ./a.out Enter the Row size for First Matrix(1-100): 3 Enter the Column Size for First Matrix(1-100): 2 Enter the Row size for Second Matrix(1-100): 2 Enter the Column Size for Second Matrix(1-100): 3 Enter Elements for the First Matrix(X) of Size 3X2: 1 2 3 4 5 6 Enter Elements for the Second Matrix(Y) of Size 2X3: 7 8 9 10 11 12 Mutliplication of Two Matrices (Z=X*Y) is : 27 30 33 61 68 75 95 106 117 $ $ ./a.out Enter the Row size for First Matrix(1-100): 3 Enter the Column Size for First Matrix(1-100): 3 Enter the Row size for Second Matrix(1-100): 3 Enter the Column Size for Second Matrix(1-100): 3 Enter Elements for the First Matrix(X) of Size 3X3: 8 2 3 7 5 4 3 8 2 Enter Elements for the Second Matrix(Y) of Size 3X3: 9 2 7 7 4 6 1 3 8 Mutliplication of Two Matrices (Z=X*Y) is : 89 33 92 102 46 111 85 44 85 $ |
As we can see from the above output, The program is properly performing the multiplication of matrices.
Test 2: Negative cases:
1 2 3 4 5 6 7 8 9 10 11 12 |
$ ./a.out Enter the Row size for First Matrix(1-100): 5 Enter the Column Size for First Matrix(1-100): 3 Enter the Row size for Second Matrix(1-100): 5 Enter the Column Size for Second Matrix(1-100): 3 ERROR: Can't Multiply Matrices, Please try again $ $ ./a.out Enter the Row size for First Matrix(1-100): 1000 Enter the Column Size for First Matrix(1-100): 4 Invalid Rows or Columns size, Please Try again $ |
2 Responses
[…] Please look at the Matrix Multiplication Program Where we explained matrix multiplication in […]
[…] C Program to Multiplication of two Matrices […]