How to create a mirror image of a 2D array in Java
Problem Statement
We have provided a list of m x n. here m indicates rows, and n indicates columns). Printing the fresh matrices should result in a mirror reflection of an old matrix.
Inverted image
The first and final columns' items are switched around in a two-dimensional array of m*n that is mirrored. According to the adjacent graphic, the central column is fixed. Keep in mind that the only modified rows are the columns of a mirror copy.
The 2nd and 4th columns will be switched if the matrix is 4*4.
Note:
The center columns would be constant, and the other columns would be switched if several such columns inside the provided matrix were odd.
![How to Create a Mirror Image of A 2D Array in Java?](https://static.tutorialandexample.com/java/how-to-create-a-mirror-image-of-a-2d-array-in-java1.png)
Java Program for finding the mirror image of the array
Example: MirrorImages.java
// this program is for finding the mirror image of the given array
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class MirrorImages
{
public static void main(String args[])
{
//establishing a new scanner instance
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the rows(r): ");
// reading the input as rows
int r = sc.nextInt();
System.out.print(" Please enter the number of the columns(c): ");
// reading the input as columns
int c = sc.nextInt();
// an array was created consisting of m*n order
int array[][] = new int[r][c];
// a new array for storing the result
int newArray[][] = new int[r][c];
System.out.println("Please enter the elements of the array");
// reading the array elements
for (int i = 0; i < r; i++)
{
System.out.println("Enter thr rows "+ (i+1) + ":");
for (int j = 0; j < c; j++)
{
array[i][j] = sc.nextInt();
}
}
// displaying the input array
System.out.println("The user input array is:");
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
// the elements of the array are exchanging
for (int j = 0; j < c; j++)
{
for (int i = 0; i < r; i++)
{
newArray[i][c - 1 - j] = array[i][j];
}
}
// displaying the out as the mirror image
System.out.println("Mirror Image of the Given Array is:");
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
System.out.print(newArray[i][j] + "\t");
}
System.out.println();
}
}
}
Output
Please enter the rows(r): 3
Please enter the number of the columns(c): 3
Please enter the elements of the arrayEnter the rows 1:
1 2 3
Enter thr rows 2:
4 5 6
Enter thr rows 3:
7 8 9
The user input array is:1
1 2 3
4 5 6
7 8 9
Mirror Image of the Given Array is:
3 2 1
6 5 4
9 8 7