Write a C program to perform matrix multiplication:

 Here's a simple C program to perform matrix multiplication:


#include <studio.h>

#define ROW1 3

#define COL1 3

#define ROW2 3

#define COL2 3

int main() {

    int mat1[ROW1][COL1], mat2[ROW2][COL2], result[ROW1][COL2];

    int i, j, k;

    // Input first matrix

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

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

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

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

        }

    }

    // Input second matrix

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

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

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

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

        }

    }

    // Perform matrix multiplication

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

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

            result[i][j] = 0;

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

                result[i][j] += mat1[i][k] * mat2[k][j];

            }

        }

    }

    // Display the result

    printf("Result:\n");

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

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

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

        }

        printf("\n");

    }

    return 0;

}

In this program, we first define the sizes of the two matrices (ROW1, COL1, ROW2, and COL2). We then declare three matrices: mat1, mat2, and result. mat1 and mat2 are the input matrices, while result is the matrix that will hold the result of the matrix multiplication.

We then input the elements of mat1 and mat2 using nested loops. After that, we perform the matrix multiplication using another set of nested loops. Finally, we display the result using another set of nested loops

Post a Comment

Previous Post Next Post

Ads

Ad