Write a c program to print multiplication of 2 matrices.

Ram Pothuraju

 #include <stdio.h>


#define ROW1 3

#define COL1 3

#define ROW2 3

#define COL2 2


int main()

{

    int mat1[ROW1][COL1] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    int mat2[ROW2][COL2] = {{1, 2}, {3, 4}, {5, 6}};

    int result[ROW1][COL2] = {{0}};


    // Multiply matrices

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

    {

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

        {

            for (int k = 0; k < ROW2; k++)

            {

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

            }

        }

    }


    // Print result

    printf("Matrix multiplication result:\n");

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

    {

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

        {

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

        }

        printf("\n");

    }


    return 0;

}



In this program, we first define two matrices mat1 and mat2 with sizes ROW1xCOL1 and ROW2xCOL2, respectively. We also define a result matrix result with size ROW1xCOL2, initialized with zeroes.

We then use nested loops to iterate through each element of the result matrix, and calculate its value by multiplying the corresponding row of mat1 with the corresponding column of mat2. We store the result in the corresponding element of the result matrix.

Finally, we print the result matrix by iterating through each row and column and printing the corresponding element.

Note that matrix multiplication is a computationally intensive operation, and may not be efficient for large matrices. In practice, it is often more efficient to use specialized libraries or hardware to perform matrix multiplication.


Tags

Post a Comment

0Comments

Post a Comment (0)