LATEST PROGRAMS

Write a C program for matrix multiplication.

#include <stdio.h>

int main()
{
    int rows1, columns1, rows2, columns2;
    printf("Enter the number of rows and columns of the first matrix: ");
    scanf("%d %d", &rows1, &columns1);
    printf("Enter the number of rows and columns of the second matrix: ");
    scanf("%d %d", &rows2, &columns2);

    if (columns1 != rows2)
    {
        printf("Matrix multiplication not possible!\n");
        return 0;
    }

    int matrix1[rows1][columns1], matrix2[rows2][columns2], product[rows1][columns2];

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

    for (int i = 0; i < rows1; i++)
    {
        for (int j = 0; j < columns1; j++)
        {
            scanf("%d", &matrix1[i][j]);
        }
    }

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

    for (int i = 0; i < rows2; i++)
    {
        for (int j = 0; j < columns2; j++)
        {
            scanf("%d", &matrix2[i][j]);
        }
    }

    // Multiplying matrices
    for (int i = 0; i < rows1; i++)
    {
        for (int j = 0; j < columns2; j++)
        {
            product[i][j] = 0;
            for (int k = 0; k < columns1; k++)
            {
                product[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }

    // Printing the result
    printf("The product of the matrices is:\n");

    for (int i = 0; i < rows1; i++)
    {
        for (int j = 0; j < columns2; j++)
        {
            printf("%d ", product[i][j]);
        }
        printf("\n");
    }

    return 0;
}
02/03/2023, 12:59 am Read : 152 times