Multiply Two Matrices in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to multiply two matrices in C. The lab covers the following steps:

Read Dimensions and Elements: You will learn how to read the dimensions and elements of two matrices from user input. This step ensures that the matrices are compatible for multiplication.

Multiply Rows by Columns: You will implement the matrix multiplication algorithm, where each element of the product matrix is calculated by multiplying the corresponding rows and columns of the input matrices.

Print the Product Matrix: Finally, you will display the resulting product matrix.

By the end of this lab, you will have a solid understanding of matrix multiplication in C and be able to apply it to various applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") subgraph Lab Skills c/output -.-> lab-435191{{"`Multiply Two Matrices in C`"}} c/for_loop -.-> lab-435191{{"`Multiply Two Matrices in C`"}} c/arrays -.-> lab-435191{{"`Multiply Two Matrices in C`"}} c/user_input -.-> lab-435191{{"`Multiply Two Matrices in C`"}} c/function_parameters -.-> lab-435191{{"`Multiply Two Matrices in C`"}} end

Read Dimensions and Elements

In this step, you will learn how to read matrix dimensions and elements for matrix multiplication in C. We'll create a program that allows users to input the size and values of two matrices.

First, let's create a new C file for our matrix multiplication program:

cd ~/project
nano matrix_multiply.c

Now, add the following code to read matrix dimensions:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int rows1, cols1, rows2, cols2;

    // Read dimensions of first matrix
    printf("Enter dimensions of first matrix (rows columns): ");
    scanf("%d %d", &rows1, &cols1);

    // Read dimensions of second matrix
    printf("Enter dimensions of second matrix (rows columns): ");
    scanf("%d %d", &rows2, &cols2);

    // Check if matrices can be multiplied
    if (cols1 != rows2) {
        printf("Matrix multiplication not possible!\n");
        return 1;
    }

    printf("Matrix dimensions are valid for multiplication.\n");

    return 0;
}

Compile and run the program:

gcc matrix_multiply.c -o matrix_multiply
./matrix_multiply

Example output:

Enter dimensions of first matrix (rows columns): 2 3
Enter dimensions of second matrix (rows columns): 3 2
Matrix dimensions are valid for multiplication.

Let's break down the code:

  • We define MAX_SIZE as 100 to limit matrix dimensions
  • scanf() is used to read matrix dimensions from user input
  • We check if matrix multiplication is possible by comparing columns of first matrix with rows of second matrix
  • If dimensions are incompatible, the program prints an error message

Now, let's modify the code to read matrix elements:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int rows1, cols1, rows2, cols2;
    int matrix1[MAX_SIZE][MAX_SIZE];
    int matrix2[MAX_SIZE][MAX_SIZE];

    // Read dimensions of first matrix
    printf("Enter dimensions of first matrix (rows columns): ");
    scanf("%d %d", &rows1, &cols1);

    // Read dimensions of second matrix
    printf("Enter dimensions of second matrix (rows columns): ");
    scanf("%d %d", &rows2, &cols2);

    // Check if matrices can be multiplied
    if (cols1 != rows2) {
        printf("Matrix multiplication not possible!\n");
        return 1;
    }

    // Read elements of first matrix
    printf("Enter elements of first matrix:\n");
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols1; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix1[i][j]);
        }
    }

    // Read elements of second matrix
    printf("Enter elements of second matrix:\n");
    for (int i = 0; i < rows2; i++) {
        for (int j = 0; j < cols2; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix2[i][j]);
        }
    }

    printf("Matrices have been successfully read.\n");

    return 0;
}

Compile and run the program:

gcc matrix_multiply.c -o matrix_multiply
./matrix_multiply

Example output:

Enter dimensions of first matrix (rows columns): 2 3
Enter dimensions of second matrix (rows columns): 3 2
Enter elements of first matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter elements of second matrix:
Enter element [0][0]: 7
Enter element [0][1]: 8
Enter element [1][0]: 9
Enter element [1][1]: 10
Enter element [2][0]: 11
Enter element [2][1]: 12
Matrices have been successfully read.

Multiply Rows by Columns

In this step, you will learn how to perform matrix multiplication by multiplying rows of the first matrix with columns of the second matrix. We'll build upon the previous code to implement the matrix multiplication algorithm.

Update the matrix_multiply.c file to add matrix multiplication functionality:

cd ~/project
nano matrix_multiply.c

Replace the previous code with the following implementation:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int rows1, cols1, rows2, cols2;
    int matrix1[MAX_SIZE][MAX_SIZE];
    int matrix2[MAX_SIZE][MAX_SIZE];
    int result[MAX_SIZE][MAX_SIZE];

    // Read dimensions of first matrix
    printf("Enter dimensions of first matrix (rows columns): ");
    scanf("%d %d", &rows1, &cols1);

    // Read dimensions of second matrix
    printf("Enter dimensions of second matrix (rows columns): ");
    scanf("%d %d", &rows2, &cols2);

    // Check if matrices can be multiplied
    if (cols1 != rows2) {
        printf("Matrix multiplication not possible!\n");
        return 1;
    }

    // Read elements of first matrix
    printf("Enter elements of first matrix:\n");
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols1; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix1[i][j]);
        }
    }

    // Read elements of second matrix
    printf("Enter elements of second matrix:\n");
    for (int i = 0; i < rows2; i++) {
        for (int j = 0; j < cols2; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix2[i][j]);
        }
    }

    // Multiply matrices
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols2; j++) {
            result[i][j] = 0;
            for (int k = 0; k < cols1; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }

    // Print result matrix
    printf("\nResult Matrix:\n");
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols2; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Compile and run the program:

gcc matrix_multiply.c -o matrix_multiply
./matrix_multiply

Example output:

Enter dimensions of first matrix (rows columns): 2 3
Enter dimensions of second matrix (rows columns): 3 2
Enter elements of first matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter elements of second matrix:
Enter element [0][0]: 7
Enter element [0][1]: 8
Enter element [1][0]: 9
Enter element [1][1]: 10
Enter element [2][0]: 11
Enter element [2][1]: 12

Result Matrix:
58 64
139 154

Let's break down the matrix multiplication algorithm:

  • The outer two loops i and j iterate through the result matrix
  • The inner loop k performs dot product of row i from the first matrix and column j from the second matrix
  • result[i][j] is calculated by summing the products of corresponding elements
  • The nested loops ensure each element of the result matrix is computed correctly

Key points about matrix multiplication:

  • The number of columns in the first matrix must equal the number of rows in the second matrix
  • The resulting matrix will have dimensions (rows of first matrix) × (columns of second matrix)

Print the Product Matrix

In this final step, we'll enhance our matrix multiplication program by adding more robust printing functionality and error handling. We'll create functions to print matrices and improve the overall user experience.

Update the matrix_multiply.c file with the following improved implementation:

cd ~/project
nano matrix_multiply.c

Replace the previous code with this comprehensive version:

#include <stdio.h>

#define MAX_SIZE 100

// Function to print a matrix
void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int rows, int cols, const char* matrixName) {
    printf("\n%s Matrix:\n", matrixName);
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%5d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int rows1, cols1, rows2, cols2;
    int matrix1[MAX_SIZE][MAX_SIZE];
    int matrix2[MAX_SIZE][MAX_SIZE];
    int result[MAX_SIZE][MAX_SIZE];

    // Read dimensions of first matrix
    printf("Enter dimensions of first matrix (rows columns): ");
    scanf("%d %d", &rows1, &cols1);

    // Read dimensions of second matrix
    printf("Enter dimensions of second matrix (rows columns): ");
    scanf("%d %d", &rows2, &cols2);

    // Check if matrices can be multiplied
    if (cols1 != rows2) {
        printf("Matrix multiplication not possible!\n");
        printf("Columns of first matrix (%d) must equal rows of second matrix (%d).\n", cols1, rows2);
        return 1;
    }

    // Read elements of first matrix
    printf("Enter elements of first matrix:\n");
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols1; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix1[i][j]);
        }
    }

    // Read elements of second matrix
    printf("Enter elements of second matrix:\n");
    for (int i = 0; i < rows2; i++) {
        for (int j = 0; j < cols2; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix2[i][j]);
        }
    }

    // Print input matrices
    printMatrix(matrix1, rows1, cols1, "First Input");
    printMatrix(matrix2, rows2, cols2, "Second Input");

    // Multiply matrices
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols2; j++) {
            result[i][j] = 0;
            for (int k = 0; k < cols1; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }

    // Print result matrix
    printMatrix(result, rows1, cols2, "Product");

    return 0;
}

Compile and run the program:

gcc matrix_multiply.c -o matrix_multiply
./matrix_multiply

Example output:

Enter dimensions of first matrix (rows columns): 2 3
Enter dimensions of second matrix (rows columns): 3 2
Enter elements of first matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter elements of second matrix:
Enter element [0][0]: 7
Enter element [0][1]: 8
Enter element [1][0]: 9
Enter element [1][1]: 10
Enter element [2][0]: 11
Enter element [2][1]: 12

First Input Matrix:
    1     2     3
    4     5     6

Second Input Matrix:
    7     8
    9    10
   11    12

Product Matrix:
   58    64
  139   154

Key improvements in this version:

  • Created a printMatrix() function to print matrices with consistent formatting
  • Added more descriptive error messages for matrix multiplication compatibility
  • Prints input matrices before showing the product matrix
  • Uses %5d for aligned matrix printing
  • Provides a clear, readable output format

Explanation of the printing function:

  • printMatrix() takes the matrix, its dimensions, and a name as parameters
  • Uses nested loops to print each element
  • %5d format specifier ensures each number takes 5 spaces for alignment
  • Adds a newline after each row for better readability

Summary

In this lab, you will learn how to read matrix dimensions and elements, and then perform matrix multiplication in C. First, you will learn how to read the dimensions of two matrices and check if they are compatible for multiplication. Then, you will learn how to read the elements of the two matrices and store them in 2D arrays. Finally, you will learn how to perform the actual matrix multiplication and print the resulting product matrix.

Other C Tutorials you may like