C++ Program to Interchange Matrix Diagonals

Write a C++ Program to Interchange Matrix Diagonals with an example. In this diagonal interchange example, we used the If statement to check whether the given matrix is square.

The first for loop within this If statement uses the temp variable to interchange the matrix diagonal. And the other nested for loop will display the Matrix Items after Interchanging Diagonals.

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns, temp;
	
	cout << "\nEnter Matrix rows and Columns to interchange Diagonals =  ";
	cin >> i >> j;
	
	int intDiagMat[i][j];
	
	cout << "\nPlease Enter the intDiagMat Matrix Items\n";
	for(rows = 0; rows < i; rows++)	
	{
		for(columns = 0; columns < i; columns++) 
		{
			cin >> intDiagMat[rows][columns];
		}		
	}	
	
	if(rows == columns)
  	{
  		for(rows = 0; rows < i; rows++)
  		{
  			temp = intDiagMat[rows][rows];
  			intDiagMat[rows][rows] = intDiagMat[rows][i - rows - 1];
  			intDiagMat[rows][i - rows - 1] = temp;
	   	}		
  	  
 		cout << "\nThe intDiagMat Matrix Items after Interchanging Diagonals are:\n";
 		for(rows = 0; rows < j; rows++)
  		{
   			for(columns = 0; columns < i; columns++)
    		{
      			cout << intDiagMat[rows][columns] << " ";
    		}
    		cout << "\n";
  		}
  	}
  	else
  	{
  		cout << "\nThe Matrix that you entered is Not a Square matrix" ;
	}	

 	return 0;
}
C++ Program to Interchange Matrix Diagonals 1

C++ Program to Interchange Matrix Diagonals using Functions

Please refer C++ programs

#include<iostream>
using namespace std;

void interchangeDiagonols(int intDiagMat[50][50], int i, int j)
{
	int rows, columns, temp;
	
	for(rows = 0; rows < i; rows++)
  		{
  			temp = intDiagMat[rows][rows];
  			intDiagMat[rows][rows] = intDiagMat[rows][i - rows - 1];
  			intDiagMat[rows][i - rows - 1] = temp;
	   	}		
  	  
 		cout << "\nThe intDiagMat Matrix Items after Interchanging Diagonals are:\n";
 		for(rows = 0; rows < j; rows++)
  		{
   			for(columns = 0; columns < i; columns++)
    		{
      			cout << intDiagMat[rows][columns] << " ";
    		}
    		cout << "\n";
  		}
}
int main()
{
	int i, j, rows, columns, intDiagMat[50][50];
	
	cout << "\nEnter Matrix rows and Columns to interchange Diagonals =  ";
	cin >> i >> j;
	
	cout << "\nPlease Enter the intDiagMat Matrix Items\n";
	for(rows = 0; rows < i; rows++)	
	{
		for(columns = 0; columns < i; columns++) 
		{
			cin >> intDiagMat[rows][columns];
		}		
	}	
	
	if(rows == columns)
  	{
  		interchangeDiagonols(intDiagMat, i, j);
  	}
  	else
  	{
  		cout << "\nThe Matrix that you entered is Not a Square matrix" ;
	}	

 	return 0;
}
Enter Matrix rows and Columns to interchange Diagonals =  3 3

Please Enter the intDiagMat Matrix Items
10 20 30
55 77 88
99 66 44

The intDiagMat Matrix Items after Interchanging Diagonals are:
30 20 10 
55 77 88 
44 66 99