C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Matrix multiplication (2D array)

C Program: Matrix Multiplication (2D array)

C

#include <stdio.h>

 

int main() {

    int a[10][10], b[10][10], result[10][10];

    int i, j, k;

    int rows1, cols1, rows2, cols2;

 

    // Input dimensions of first matrix

    printf("Enter number of rows and columns of first matrix: ");

    scanf("%d %d", &rows1, &cols1);

 

    // Input dimensions of second matrix

    printf("Enter number of rows and columns of second matrix: ");

    scanf("%d %d", &rows2, &cols2);

 

    // Check matrix multiplication condition

    if (cols1 != rows2) {

        printf("\nMatrix multiplication not possible! Columns of first must equal rows of second.\n");

        return 0;

    }

 

    // Input first matrix

    printf("\nEnter elements of first matrix:\n");

    for (i = 0; i < rows1; i++) {

        for (j = 0; j < cols1; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    // Input second matrix

    printf("\nEnter elements of second matrix:\n");

    for (i = 0; i < rows2; i++) {

        for (j = 0; j < cols2; j++) {

            scanf("%d", &b[i][j]);

        }

    }

 

    // Initialize result matrix to zero

    for (i = 0; i < rows1; i++) {

        for (j = 0; j < cols2; j++) {

            result[i][j] = 0;

        }

    }

 

    // Perform matrix multiplication

    for (i = 0; i < rows1; i++) {

        for (j = 0; j < cols2; j++) {

            for (k = 0; k < cols1; k++) {

                result[i][j] += a[i][k] * b[k][j];

            }

        }

    }

 

    // Display resulting matrix

    printf("\nResultant Matrix (Product):\n");

    for (i = 0; i < rows1; i++) {

        for (j = 0; j < cols2; j++) {

            printf("%d\t", result[i][j]);

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
INPUT :
Enter number of rows and columns of first matrix: 2 3
Enter number of rows and columns of second matrix: 3 2

Enter elements of first matrix:
1 2 3
4 5 6

Enter elements of second matrix:
7 8
9 10
11 12

OUTPUT :
Resultant Matrix (Product):
58   64
139  154

Explanation

  1. Condition for multiplication → Columns of first matrix = Rows of second matrix.
  2. Each element of the resulting matrix is calculated using:

 C Programs

  1. The result is stored in result[i][j].
  2. Finally, the product matrix is displayed.