By multiplying a matrix A of dimensions R and C with a matrix B of dimensions C and P, a matrix MULT of dimensions R and P is obtained:
A (R, C) * B (C, P) = MULT (R, P)
The multiplication of two matrices is done by multiplying the components of the two matrices rows by columns:
\(MULT_{ij}=(\sum_{k=1}^{C}a_{ik}\times b_{kj})\)
Write a program that performs the multiplication of two matrices A and B. The result of the multiplication will be stored in a third matrix MULT which will then be displayed.
\(\begin{pmatrix} a & b & c \\e & f & g \\ h & i & j \\ h & l & m \end{pmatrix} \times \begin{pmatrix} p & q \\ r &s \\ t & u \end{pmatrix} = \begin{pmatrix} a \times p + b \times r + c \times t & a \times q + b \times s + c \times u \\ e \times p + f \times r + g \times t & e \times q + f \times s + g \times u \\ h \times p + i \times r + j \times t & h \times q + i \times s + j \times u \\ k \times p + l \times r + m \times t & k \times q + l \times s + m \times u \end{pmatrix}\)
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define SIZE 50
main()
{
int A[SIZE][SIZE];
int B[SIZE][SIZE];
int MULT[SIZE][SIZE];
int R, C, P;
int I, J, K;
printf("*** Matrix A ***\n");
do {
printf("Number of rows of A (max.%d) : ", SIZE);
scanf("%d", &R);
} while (R <= 0 || R > SIZE);
do {
printf("Number of columns of A (max.%d) : ", SIZE);
scanf("%d", &C);
} while (C <= 0 || C > SIZE);
for (I = 0; I<R; I++)
for (J = 0; J<C; J++)
{
printf("A[%d][%d] : ", I, J);
scanf("%d", &A[I][J]);
}
printf("*** Matrix B ***\n");
printf("Number of rows of B : %d\n", C);
printf("Number of columns of B (max.%d) : ", SIZE);
scanf("%d", &P);
for (I = 0; I<C; I++)
for (J = 0; J<P; J++)
{
printf("B[%d][%d] : ", I, J);
scanf("%d", &B[I][J]);
}
printf("Matrix A :\n");
for (I = 0; I<R; I++)
{
for (J = 0; J<C; J++)
printf("%7d", A[I][J]);
printf("\n");
}
printf("Matrix B :\n");
for (I = 0; I<C; I++)
{
for (J = 0; J<P; J++)
printf("%7d", B[I][J]);
printf("\n");
}
/* Multiplication */
for (I = 0; I<R; I++)
for (J = 0; J<P; J++)
{
MULT[I][J] = 0;
for (K = 0; K<C; K++)
MULT[I][J] += A[I][K] * B[K][J];
}
printf("Resultant matrix :\n");
for (I = 0; I<R; I++)
{
for (J = 0; J<P; J++)
printf("%7d", MULT[I][J]);
printf("\n");
}
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Solitaire Card Game