Mirror Image of Matrix in Java Trick 2024
Note:
Mirror image of matrix means you have to interchange the position of all the columns, meaning change the 1st columns to last column and vice versa, same is true for other columns
If you are not able to understand the above
definition, then look at the example given
below.
Algorithm to Print Mirror Image of Matrix:-
Step 1: Input number of rows (r).
Step 2: Input number of columns (c).
Step 3: Input elements of the Matrix.
Step 4: Interchange the columns of the input matrix.
Step 5: Print the mirror image of the matrix.
Below, In this post, I have written a short and easy-to-understand java program which accepts elements of a matrix from the user using scanner input and prints the mirror image of the input matrix.
The logic I have implemented in this program is pretty easy to understand.
First, I will ask the user to enter the number of rows and
columns then, the user will enter the elements of the matrix, and after that, I will access the columns of the input matrix to mirror it using for loop print it.
Mirror Image of Matrix in Java
import java.util.*;
class Mirror_Matrix
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of Rows");
int r=sc.nextInt();
System.out.println("Enter the number of Columnns");
int c=sc.nextInt();
int arr[][]=new int[r][c];
System.out.println("Enter the elements of Matrix");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println("Input Matrix is:");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println(" ");
}
System.out.println("Mirror Matrix is:");
for(int i=0;i<r;i++)
{
for(int j=c-1;j>=0;j--)
{
System.out.print(arr[i][j]+" ");
}
System.out.println(" ");
}
}
}
------------
OUTPUT:-
-----------
Enter the number of Rows
4
Enter the number of Columns
4
Enter the elements of Matrix
1
5
9
8
7
5
3
2
4
6
8
5
2
1
4
5
Input Matrix Is:
1 5 9 8
7 5 3 2
4 6 8 5
2 1 4 5
Mirror Matrix is:
8 9 5 1
2 3 5 7
5 8 6 4
5 4 1 2
0 Comments
Just write down your question to get the answer...