Write a program that interchanges the diagonals of a square matrix.

\(\begin{pmatrix} a & b & c \\d & e & f \\ g & h & i  \end{pmatrix} becomes \begin{pmatrix} c & b & a \\d & e & f \\ i & h & g \end{pmatrix} \)


Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define SIZE 50
void main()
{
	int A[SIZE][SIZE];
	int dim;        /* dimensions */
	int I, J, aux;             
			
	do {
		printf("Number of rows/columns   (max.%d) : ", SIZE);
		scanf("%d", &dim);
	} while (dim <= 0 || dim > SIZE);
 

	printf("*** Matrix ***\n");
	for (I = 0; I<dim; I++)
		for (J = 0; J<dim; J++)
		{
			printf("A[%d][%d] : ", I, J);
			scanf("%d", &A[I][J]);
		}

 

	printf("Before the exchange :\n");
	for (I = 0; I<dim; I++)
	{
		for (J = 0; J<dim; J++)
			printf("%6d", A[I][J]);
		printf("\n");
	}

	// we loop over the rows
	for (I = 0; I<dim; I++)
	{
		// we exchange the element at index I with element at index dim - I - 1
		aux = A[I][I];
		A[I][I] = A[I][dim - I - 1];
		A[I][dim - I - 1] = aux;
	}
	
	printf("After the exchange  :\n");
	for (I = 0; I<dim; I++)
	{
		for (J = 0; J<dim; J++)
			printf("%6d", A[I][J]);
		printf("\n");
	}
 

	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Forest of Binary Search Trees