Write the function SUM_MATRIX of the long type which calculates the sum of the elements of a MAT matrix of the type int. Choose the necessary parameters. Write a small program that tests the function SUM_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");
	}
}

long SUM_MATRIX(int MAT[][N], int R, int C)
{
	int I, J;
	long SUM = 0;

	for (I = 0; I<R; I++)
		for (J = 0; J<C; J++)
			SUM += MAT[I][J];
	return SUM;
}


void main()
{
	int Mat[N][N], R, C;
	R = READ_NB_ROWS(N);
	C = READ_NB_COLUMNS(N);
	READ_MATRIX(Mat, R, C);
	PRINT_MATRIX(Mat, R, C);
	printf("Sum of elements : %ld\n", SUM_MATRIX(Mat, R, C));
	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
ADT for a set of pairs of values