Posted on by Kalkicode
Code Matrix

Swap diagonal elements in matrix

The problem involves swapping the diagonal elements of a given matrix. This means exchanging the values of the elements on the main diagonal (from top-left to bottom-right) with the values of the elements on the secondary diagonal (from top-right to bottom-left). This operation can be done using a recursive approach, which is what this a program demonstrates.

Problem Statement

Given an N x N matrix, we need to swap its diagonal elements using a recursive approach and display the resulting matrix.


Consider the following matrix:

1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16

After swapping the diagonal elements, the matrix becomes:

4  2  3  1
5  7  6  8
9  11 10 12
16 14 15 13

Idea to Solve the Problem

Example to interchange the diagonal of matrix

The idea to solve this problem is to use a recursive approach. We start by swapping the elements at the corners of the matrix (top-left and bottom-right). Then, we move inwards towards the center of the matrix, swapping the corresponding elements from both diagonals. This process continues recursively until we've covered all the elements along the diagonals.


  1. Define a function swapDiagonal that takes the matrix and four indices (x, y, p, q) as parameters. These indices represent the top-left and bottom-right corners of the current submatrix to be swapped.
  2. If x >= y or p >= q, it means we have finished swapping for the current submatrix, so return.
  3. Swap the elements at (x, p) with (x, q) and (y, p) with (y, q).
  4. Recursively call swapDiagonal with incremented x and y, and decremented p and q.
  5. Display the matrix using the showMatrix function.
  6. In the main function, define the input matrix and call the swapDiagonal function with appropriate initial indices.
  7. Display the original and modified matrices using the showMatrix function.

Code Solution

Time Complexity

The time complexity of this solution is O(N), where N is the number of elements in the matrix. This is because each element is swapped only once.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment