×

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in a matrix, the algorithm to be followed and also a simple example program in java.

What is a Matrix in java?

Technically referring, a matrix is a rectangular, two-dimensional array that contains either integers, symbols, or statements as its fundamental elements. The elements in the matrix are arranged in rows and columns.

For an instance, m  x n matrix refers to a matrix containing 'm' number of rows and 'n' number of columns. 'a [i][j]', which denotes that the element an is represented in the i-th row and j-th column, can be used to represent individual values in the matrix, which are referred to as elements.

Look at the example below to understand how a matrix actually looks like

Example:

                              A[][]= { 7, 8, 9,

                                    4, 5, 6,

                                    1, 2, 3}

The above example is a matrix or it can also be termed as two-dimensional array, with 3 rows and 3 columns.

Now let us understand what is meant by interchanging the diagonal elements.

Interchanging the diagonal elements in an array means to swap the elements contained in left diagonal to right diagonal and swap the elements contained in the right diagonal to the left diagonal.

Note:  The interchanging can only happen when the matrix has the same number of rows and columns. Else interchanging the diagonal elements would not be possible. Even of possible, the interchanging cannot be very accurate and perfect.

Let us discuss an example that can be easily understood.

Consider a 4x4 matrix with

     a[][]=  { 7, 8, 9, 10,

                 4, 5, 6, 11,

                 1, 2, 3, 12

                  13, 14, 15,16  }

In the above matrix, interchanging of elements from left and right diagonal would happen as follows:

a[1][1] would swap with a[1][4]

a[2][2] would swap with a[2][3]

a[3][3] would swap with a[3][2]

a[4][4] would swap with a[4][1]

We notice that there is only difference in the row index between the left and right diagonals and there is no change in column index. If we pay close attention to the column indices, we can see a pattern where the column index mostly on left side is advancing by 1 and the column index on the right side is reducing by 1.

Therefore, the simple logic to interchange the diagonal elements is as follows

for(initialization; condition; increment/decrement)
{
Swap(a[i][i], a[i][n-i-1]); // where ‘n’ is the size of matrix
}

Algorithm

The below is the algorithm or step by step instruction that has to be followed when interchanging the diagonal elements of a given matrix.

  • Initialize variables for size of the matrix.
  • Seeking the user to set the matrix's rows and columns to zero
  • Verify whether the total number of rows and columns is the same.
  • The user is asked to initialise the matrix if the results are equal.
  • Generate the matrix as it is.
  • Change the diagonal units.
  • Print the matrix with the diagonals switched.
  • Print the identical statement if the columns and the rows are not equal.

Now let us understand how interchanging of diagonal elements work with the help of an example program.

File name: Swapelem.java

import java.util.Scanner;  
public class Swapelem 
{  
    public static void main(String args[])  
    {  
        Scanner s = new Scanner(System.in);  
        System.out.print("Enter the number of rows and columns: ");  
        //Obtaining the input from the user  
        int n=s.nextInt();  
        //constructing a matrix of size n*n  
        int a[][] = new int [n][n];  
        //Matrix elements taken as input 
        System.out.println("Enter the elements of the matrix: ");  
        for(int i=0; i<n; i++)  
        {  
            for(int j=0; j<n; j++)  
            {    
                a[i][j]=s.nextInt();  
            }  
        }  
        //Displaying the actual matrix  
        System.out.println("\n Actual matrix: \n");  
        for(int i=0; i<n; i++)  
        {  
            for(int j=0; j<n; j++)  
            {  
                 System.out.print(a[i][j]+"\t");  
            }  
            System.out.println(" ");  
        }  
        //elements interchanging
        for(int i=0; i<n; i++)  
        {  
            int temp = a[i][i];  
            a[i][i] = a[i][n-i-1];  
            a[i][n-i-1] = temp;  
        }  
      //prints the diagonal interchanged matrix  
 System.out.println("\n Matrix after the diagonals are interchanged: \n");  
        for(int i=0; i<n; i++)  
        {  
            for(int j=0; j<n; j++)  
            {  
                 System.out.print(a[i][j]+"\t");  
            }  
            System.out.println(" ");  
        }  
    }  
}  

Output:

Enter the number of rows and columns: 3
Enter the elements of the matrix:
1
2
3
4
5
6
7
8
9


Actual matrix:


1       2       3
4       5       6
7       8       9


Matrix after the diagonals are interchanged:


3       2       1
4       5       6
9       8       7

Time Complexity

The time complexity is O(n*n) because we have included nested loops for traversing through the matrix.

Space Complexity

The space complexity is O(1) because any extra space is not used in allocating the memory.


Related Topics

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.