Matrix Multiplication in C

CCBeginner
Practice Now

Introduction

In this lab, we are going to write a matrix multiplication program in C. We will learn how to create a matrix, perform matrix operations, and discuss the standard algorithm for matrix multiplication. We'll create a C program to multiply two matrices and print the resulting matrix.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/comments("`Comments`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/PointersandMemoryGroup -.-> c/memory_address("`Memory Address`") c/PointersandMemoryGroup -.-> c/pointers("`Pointers`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") c/FunctionsGroup -.-> c/recursion("`Recursion`") subgraph Lab Skills c/output -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/comments -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/variables -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/data_types -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/operators -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/if_else -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/for_loop -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/user_input -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/memory_address -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/pointers -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/function_parameters -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/function_declaration -.-> lab-123281{{"`Matrix Multiplication in C`"}} c/recursion -.-> lab-123281{{"`Matrix Multiplication in C`"}} end

Creating matrices

First, let's learn how to create matrices. A matrix is a two-dimensional array. Here is an example of how to declare and initialize a 2x2 matrix in C:

int matrix[2][2] = {{1, 2}, {3, 4}};

We can access specific elements of the matrix using two indices, as in the following example:

int element = matrix[1][0];

Matrix multiplication with a scalar value

Matrix multiplication with a single value is easy and is done as follows:

int arr[2][2], n;
//Enter scalar value
scanf("%d", &n);

//Input matrix elements
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        scanf("%d", &arr[i][j]);
    }
}
// Multiply every element of the matrix with the scalar value
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        arr[i][j] = arr[i][j] * n;
    }
}

// Print the updated matrix elements
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        printf("%d ", arr[i][j]);
    }
    printf("\n");
}

The program multiplies each element of the matrix with the scalar value entered by the user and then prints the updated matrix.

Matrix multiplication with two matrices

To multiply two matrices, you need to follow certain rules. First, the number of columns of the first matrix should be equal to the number of rows of the second matrix. Second, the resultant matrix will have the same number of rows as the first matrix and the same number of columns as the second matrix.

Suppose we have two matrices:

A = {{1, 3, 5},
     {4, 2, 6}};

B = {{7, 4},
     {3, 1},
     {6, 9}};

To multiply these two matrices, we will perform a dot product on their rows and columns. The elements of the matrices are multiplied by using the following formula:

result[row][col] = matrix1[row][0] * matrix2[0][col]
                  + matrix1[row][1] * matrix2[1][col]
                  + matrix1[row][2] * matrix2[2][col]
                  + ...;

Following is a C program on Matrix Multiplication:

#include <stdio.h>

int main()
{
  int m, n, p, q, c, d, k, sum = 0;

  // define two matrices
  int first[10][10], second[10][10], result[10][10];

  // input the number of rows and columns of the first matrix
  printf("Enter the number of rows and columns of the first matrix:\n");
  scanf("%d %d", &m, &n);

  // input the elements of the first matrix
  printf("Enter the %d elements of the first matrix:\n", m * n);
  for (c = 0; c < m; c++) {
    for (d = 0; d < n; d++) {
      scanf("%d", &first[c][d]);
    }
  }

  // input the number of rows and columns of the second matrix
  printf("Enter the number of rows and columns of the second matrix:\n");
  scanf("%d %d", &p, &q);

  // input the elements of the second matrix
  printf("Enter the %d elements of the second matrix:\n", p * q);
  for (c = 0; c < p; c++) {
    for (d = 0; d < q; d++) {
      scanf("%d", &second[c][d]);
    }
  }

  // check if matrices can be multiplied
  if (n != p) {
    printf("Matrices cannot be multiplied with each other.\n");
  } else {
    // multiplying the matrices
    for (c = 0; c < m; c++) {
      for (d = 0; d < q; d++) {
        for (k = 0; k < p; k++) {
          sum = sum + first[c][k] * second[k][d];
        }
        result[c][d] = sum;
        sum = 0;
      }
    }

    // print the resulting matrix
    printf("The resulting matrix is:\n");
    for (c = 0; c < m; c++) {
      for (d = 0; d < q; d++) {
        printf("%d\t", result[c][d]);
      }
      printf("\n");
    }
  }

  return 0;
}

The program will ask the user to input the elements of two matrices, check if they can be multiplied, multiply them if possible, and print the resulting matrix.

Full program

Here is the full program combining all the steps:

#include<stdio.h>

int main()
{
    int n, m, c, d, p, q, k, first[10][10], second[10][10], pro[10][10], sum = 0;

    printf("\nEnter the number of rows and columns of the first matrix: \n\n");
    scanf("%d%d", &m, &n);

    printf("\nEnter the %d elements of the first matrix: \n\n", m*n);
    for(c = 0; c < m; c++) {
        for(d = 0; d < n; d++) {
            scanf("%d", &first[c][d]);
        }
    }

    printf("\nEnter the number of rows and columns of the first matrix: \n\n");
    scanf("%d%d", &p, &q);

    if(n != p)
        printf("Matrices with the given order cannot be multiplied with each other.\n\n");

    else {
        printf("\nEnter the %d elements of the second matrix: \n\n",m*n);

        for(c = 0; c < p; c++) {
            for(d = 0; d < q; d++) {
                scanf("%d", &second[c][d]);
            }
        }

        printf("\n\nThe first matrix is: \n\n");
        for(c = 0; c < m; c++) {
            for(d = 0; d < n; d++) {
                printf("%d\t", first[c][d]);
            }
            printf("\n");
        }

        printf("\n\nThe second matrix is: \n\n");
        for(c = 0; c < p; c++) {
            for(d = 0; d < q; d++){
                printf("%d\t", second[c][d]);
            }
            printf("\n");
        }

        for(c = 0; c < m; c++) {
            for(d = 0; d < q; d++) {
                for(k = 0; k < p; k++) {
                    sum = sum + first[c][k] * second[k][d];
                }
                pro[c][d] = sum;
                sum = 0;
            }
        }

        printf("\n\nThe multiplication of the two entered matrices is: \n\n");
        for(c = 0; c < m; c++) {
            for(d = 0; d < q; d++) {
                printf("%d\t", pro[c][d]);
            }
            printf("\n");
        }
    }
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

Summary

In this lab, we've learned how to create a matrix in C and the different types of matrix multiplication operations that we can perform. We've created a program to compute the multiplication of two matrices in C and discussed the standard algorithm for matrix multiplication.

Other C Tutorials you may like