How to reverse two dimensional array in Java

Hi learners, in this Java tutorial you will learn how to reverse a two-dimensional array in Java. I will show you how easily you can reverse two dimensional array in Java with an easy example.

If you don’t know what is a 2d array and learn how to create a 2d array in Java please¬†read this:¬†How to create a dynamic 2D array in Java

Reverse two dimensional array in Java

reverse two dimensional array in java

In this problem, we have to bring the last element to the first position and first element to the last position. And all other elements will be reversed one by one.

All we need here is just the Java util package.



So just import util package in your Java program.

Below I have provided an easy example. Let’s take a look

import java.util.*;

public class Reverse_my_array{ 
public static void reverse_it(int[][] my_array){
int my_rows = my_array.length;
    int my_cols = my_array[0].length;
    int array[][]=new int[my_rows][my_cols];
    for(int i = my_rows-1; i >= 0; i--) {
        for(int j = my_cols-1; j >= 0; j--) {
            array[my_rows-1-i][my_cols-1-j] = my_array[i][j];
        }
    }
    for(int i = 0; i < my_rows; i++) {
        for(int j = 0; j < my_cols; j++) {
            System.out.print(array[i][j]+" ");
            }
     }
}

public static void main(String[] args) throws Exception {
    int my_rows, my_cols;
    int[][] my_array;
    Scanner input = new Scanner(System.in);
    System.out.print("Enter number of rows:");
    my_rows = input.nextInt();
    System.out.print("Enter number of columns:");
    my_cols = input.nextInt();
    my_array= new int[my_rows][my_cols];
    System.out.println("Enter elements of Array");
    for (int i = 0; i < my_rows; i++) {
        for (int j = 0; j < my_cols; j++) {
            my_array[i][j] = input.nextInt();
        }
    }
    System.out.println("Array is: ");
    for (int i = 0; i < my_rows; i++) {
        for (int j = 0; j < my_cols; j++) {
        System.out.print(my_array[i][j]+" ");
        }
    }
    System.out.println();
    reverse_it(my_array);
         }
}

Here I have created this method to reverse the array:

reverse_it()

and passed a 2d array as a parameter.

 

I hope you have found this useful.
Feel free to comment if you want.

You may also read,

Guess The Number Game Using Java with Source Code

How to create a dynamic 2D array in Java

Leave a Reply

Your email address will not be published. Required fields are marked *