×

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 Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

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...

4 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.