top of page
Writer's pictureSatyam Gupta

Swapping Diagonal elements of a Matrix

Java Program To Swap Diagonal elements of a Matrix

A matrix of order N X N is given. Swap the elements of major and minor diagonals. 


Major Diagonal Elements of a Matrix are the ones that occur from Top Left of Matrix Down To Bottom Right Corner. The Major Diagonal is also known as Main Diagonal or Primary Diagonal.


Minor Diagonal Elements of a Matrix : The Minor Diagonal Elements are the ones that occur from Top Right of Matrix Down To Bottom Left Corner. Also known as Secondary Diagonal.


 

Logic and Program :-


Logic :-


Logic of the program

 

Program :-


import java.io.*; import java.util.*; class Matrix {     public static void main(String args[])     {         int n,a; // here a is the temporary variable for swapping the elements         int i,j; // variable for loop         Scanner in= new Scanner(System.in);         System.out.println("Enter Array Capacity");         n= in.nextInt(); // To Input Array Capacity         int ar[][]=new int[n][n]; // Array Defined         System.out.println("Enter Array Elements");         for(i=0;i<n;i++)         {             for(j=0;j<n;j++)             {                 ar[i][j]= in.nextInt(); // Input Array Elements             }         }         System.out.println("Original Matrix"); // Display Original Matrix         for(i=0;i<n;i++)         {             for(j=0;j<n;j++)             {                 System.out.print(ar[i][j]);             }             System.out.println();         }         int k = n-1; // Variable value used to swap value         for(i=0;i<n;i++) // Value is Swapping in this Loop         {             a = ar[i][i];             ar[i][i]=ar[i][k-i];             ar[i][k-i]=a;         }         System.out.println("New Matrix"); // Printing New Matrix After Swapping Diagonal         for(i=0;i<n;i++)         {             for(j=0;j<n;j++)             {                 System.out.print(ar[i][j]);             }             System.out.println();         }     } // End of main method } // End of class


 

Note : The program is written in the easiest way possible so try understand it. If you face any problem in understanding this program than feel free to contact/comment.


All the Best :)

Keep Learning :)

521 views0 comments

Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page