Write the function ADDITION_MATRIX which carries out the addition of the matrices following: MAT1 = MAT1 + MAT2

Choose the necessary parameters and write a small program that tests the function ADDITION_MATRIX.


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 ADDITION_MATRIX(int MAT1[][N], int MAT2[][N], int R, int C)
{
	int I, J;
	/* Add elements of MAT2 to MAT1 */
	for (I = 0; I<R; I++)
		for (J = 0; J<C; J++)
			MAT1[I][J]  += MAT2[I][J];
}

void main()
{
	int Mat1[N][N], Mat2[N][N], R, C;
	R = READ_NB_ROWS(N);
	C = READ_NB_COLUMNS(N);

	printf("*** Matrix 1 ***\n");
	READ_MATRIX(Mat1, R, C);
	PRINT_MATRIX(Mat1, R, C);
	printf("*** Matrix 2 ***\n");
	READ_MATRIX(Mat2, R, C);
	PRINT_MATRIX(Mat2, R, C);


	ADDITION_MATRIX(Mat1, Mat2, R, C);

	printf("*** Matrix 1 ***\n");
	PRINT_MATRIX(Mat1, R, C);

	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Binary search trees in levels