Write the function TRANSPO_MATRIX with 3 parameters MAT, R and C, CMAX transposes the MAT matrix.

TRANSPO_MATRICE returns a logical value which indicates if the dimensions of the matrix are such that the transposition could be carried out.

Write a small program that tests the TRANSPO_MATRICE function.


Difficulty level
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");
	}
}

int TRANSPO_MATRIX(int MAT[][N], int R, int C)
{

	int I, J;
	int DMAX; /* the biggest of the 2 dimensions */
	int aux;
		 
	if (R>N || C>N)
		return 0;
	else
	{
		DMAX = (R>C) ? R : C;
		for (I = 0; I<DMAX; I++)
			for (J = 0; J < I; J++)
			{
				aux = MAT[I][J];
				MAT[I][J]= MAT[J][I];
				MAT[J][I] = aux;
			}
		return 1;
	}
}

void main()
{
	int Mat[N][N], R, C;
	int aux;
	R = READ_NB_ROWS(N);
	C = READ_NB_COLUMNS(N);
	READ_MATRIX(Mat, R, C);
	PRINT_MATRIX(Mat, R, C);

	if (TRANSPO_MATRIX(Mat, R,C))
	{
		printf("Transpose of the matrix : \n");
		// we need to exhcnage the dimensions
		aux = R;
		R = C;
		C = aux;
		PRINT_MATRIX(Mat, R, C);
	}
	else
		printf("\aCannot transpose the matrix.\n");

	

	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implement a stack using a heap