Multiplication of Two Matrices in C Program

Multiplication-of-Two-Matrices-in-C

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 )

Matrix – Y: ( 2X2 )

Multiplication of Two Matrices X and Y is ( X * Y) :

Please look at the following graphical explanation.

multiplication-of-two-matrices-in-c

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

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.

  1. 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)
  2. 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.
  3. 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)
  4. 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.
  5. Repeat the Step-3 and Step-4 for Second Matrix-Y
  6. 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.
  7. 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
  8. 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
  9. Repeat the Step 8 to Take the Second Matrix ( Matrix-Y) elements from the user.
  10. To Calculate the Multiplication of Two Matrices in C, We need to go through the all elements of the matrices using the loops
  11. 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.
  12. Once the above <b>Step 11</b> is finished, The Matrix-Z contains the Multiplication result of Matrix-X and Matrix-Y.
  13. Display the Results( Maxtrix-Z) using loops and printf function.
  14. 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.

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.

Test Case 2: When the First Matrix and Second Matrix has different row and columns Size

matrix-multiplication-program-in-c-output

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.

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).

The functions are

  1. The readMatrix() function – Used to read the matrix elements from the user and update the given matrix
    • Function Prototypevoid 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).
  2. 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]);
  3. The multiplyMatrices() function – This function performs the multiplication operation of the Matrix-X and Matrix-Y
    • Function Prototypevoid 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-ZZ[i][j] += X[i][k] * Y[k][j];

Program Output:

Let’s compile and run the program.

Test 1: Normal cases:

matrix-multiplication-using-functions-program-output

As we can see from the above output, The program is properly performing the multiplication of matrices.

Test 2: Negative cases:

Related Matrix Programs:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

2 Responses

  1. […] Please look at the Matrix Multiplication Program Where we explained matrix multiplication in […]

  2. […] C Program to Multiplication of two Matrices […]

Leave a Reply