Write the function MULTI_2_MATRICES which performs the multiplication of two matrices MAT1 (dimensions R and P) and MAT2 (dimensions P and C) in a third matrix MAT3 (dimensions R and C): MAT3 = MAT1 * MAT2

Suppose that the maximum dimensions of the three matrices are all equal to 30 rows and 30 columns. Write a small program that tests the MULTI_2_MATRICES function.


Difficulty level
Video recording
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define N 100

int READ_NB_ROWS(int Rmax)
{
	int R;
	do
	{
		printf("Number of rows    (max.%d) : ", Rmax);
		scanf("%d", &R);
	} while (R<0 || R>Rmax);
	return R;
}

int READ_NB_COLUMNS(int Cmax)
{
	int C;
	do
	{
		printf("Number of columns (max.%d) : ", Cmax);
		scanf("%d", &C);
	} while (C<0 || C>Cmax);
	return C;
}

void READ_MATRIX(int MAT[][N], int R, int C)
{
	int I, J;
	for (I = 0; I<R; I++)
		for (J = 0; J<C; J++)
		{
			printf("Element[%d][%d] : ", I, J);
			scanf("%d", &MAT[I][J]);
		}
}

void PRINT_MATRIX(int MAT[][N], int R, int C)
{
	int I, J;
	for (I = 0; I < R; I++)
	{
		for (J = 0; J < C; J++)
			printf("%7d", MAT[I][J]);
		printf("\n");
	}
}

void MULTI_2_MATRICES(int MAT1[][N], int MAT2[][N], int MAT3[][N], int R, int P, int C)
{
	int I, J, K;
	for (I = 0; I<R; I++)
		for (J = 0; J<C; J++)
		{
			MAT3[I][J] = 0;
			for (K = 0; K<P; K++)
				MAT3[I][J] += MAT1[I][K] * MAT2[K][J];
		}
}

void main()
{
	int Mat1[N][N], Mat2[N][N], Mat3[N][N], R, P, C;

	printf("*** Matrix 1 ***\n");
	R = READ_NB_ROWS(N);
	P = READ_NB_COLUMNS(N);
	READ_MATRIX(Mat1, R, P);
	PRINT_MATRIX(Mat1, R, P);
	printf("*** Matrix 2 ***\n");
	C = READ_NB_COLUMNS(N);
	READ_MATRIX(Mat2, P, C);
	PRINT_MATRIX(Mat2, P, C);


	MULTI_2_MATRICES(Mat1, Mat2, Mat3, R, P, C);

	printf("*** Matrix 3 ***\n");
	PRINT_MATRIX(Mat3, R, C);

	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Search into a table based on hash coalesced with separated zones