Multiplication of Two Matrices in C

Multiplication of Two Matrices in C

The following C code calculates the multiplication of two 2×2 matrices. The program prompts the user to input values for the first matrix and then asks for the values for the second matrix. It performs the matrix multiplication using nested for loops. The resulting matrix is then printed on the console. The code adheres to modern C programming standards, employing printf and scanf for input and output operations.

The outer loop iterates through each row of the first matrix, and another set of loops iterates through each column of the second matrix. During this process, the product of corresponding elements from the current row and column is accumulated to calculate the final value in the result matrix.

#include <stdio.h>

int main() {
    int mat1[2][2], mat2[2][2], mat3[2][2], i, j, k;

    // Input for the first matrix
    printf("Enter values for the first matrix:\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            printf("Enter the value for row %d, column %d: ", i + 1, j + 1);
            scanf("%d", &mat1[i][j]);
        }
    }

    // Input for the second matrix
    printf("\nEnter values for the second matrix:\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            printf("Enter the value for row %d, column %d: ", i + 1, j + 1);
            scanf("%d", &mat2[i][j]);
        }
    }

    // Displaying the given matrices
    printf("\nThe given matrices are:\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            printf("%d\t", mat1[i][j]);
        }
        printf("\n");
    }

    printf("\n");

    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            printf("%d\t", mat2[i][j]);
        }
        printf("\n");
    }

    // Matrix multiplication
    printf("\nThe multiplication of the matrices is:\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            mat3[i][j] = 0;
            for (k = 0; k < 2; k++) {
                mat3[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }

    // Displaying the result
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            printf("%d\t", mat3[i][j]);
        }
        printf("\n");
    }

    return 0;
}
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post