Site icon TestingDocs.com

Array reflection in the mirror java program?

Problem statement

Array reflection in the mirror. Write a java program to reverse an array i.e from top to bottom, exchange the first row for the last row, the second row for the second to last row, and so on until the entire array is reversed.

Note: I recommend the reader to try the program for practice, before reading down my solution.

Java Program:

Assume array size 10×10. Lets write the java program to display the array and its reflection in the mirror. In this program, the array will be filled with random numbers.

package com.testingdocs.sample;

public class MirrorArrayExample {
 static int[][] array ;
 public static void main(String[] args) {
 // Array of size 10x10
 int n = 10;
 array = fillRandomArray(n);
 printArray(array);

System.out.println("Mirror" + "----------------------------------------------------------------");
 mirrorArray(array);
 printArray(array);

}

// fill the array with Random numbers from 0-9
 static int[][] fillRandomArray(int n) {
 int[][] a = new int[n][n];
 for(int i=0;i<n;i++)
 {
 for(int j=0;j<n;j++)
 {
 a[i][j] = getRandom(10);
 }
 }
 return a;
 }

// print the array 
 static int[][] printArray(int[][] a)
 {
 for(int i=0;i< a.length;i++)
 {
 for(int j=0;j<a.length;j++)
 {
 System.out.print(" " + a[i][j]);
 }
 System.out.println();
 }
 return a;
 }

static int getRandom(int max){
 return (int) (Math.random()*max);
 }

static void mirrorArray(int [][] a) {

for(int i = 0; i < (a.length/2); i++) {
 int[] temp = a[i];
 a[i] = a[a.length - i - 1];
 a[a.length - i - 1] = temp;
 }
 }
}

 

Output of the program

6 5 0 7 1 2 7 0 5 4
0 8 9 7 3 8 8 9 0 1
0 7 9 4 7 3 3 7 6 4
1 1 5 3 4 8 5 2 4 7
4 0 8 9 2 2 6 4 8 8
6 0 6 7 0 8 9 8 5 1
2 1 0 9 9 1 3 5 3 7
7 0 7 3 1 9 9 5 2 9
6 2 1 7 1 0 0 9 0 5
5 7 0 3 7 1 2 3 9 2
Mirror—————————————————————-
5 7 0 3 7 1 2 3 9 2
6 2 1 7 1 0 0 9 0 5
7 0 7 3 1 9 9 5 2 9
2 1 0 9 9 1 3 5 3 7
6 0 6 7 0 8 9 8 5 1
4 0 8 9 2 2 6 4 8 8
1 1 5 3 4 8 5 2 4 7
0 7 9 4 7 3 3 7 6 4
0 8 9 7 3 8 8 9 0 1
6 5 0 7 1 2 7 0 5 4

Screenshot

Exit mobile version