Answer:
//The Scanner class is imported to allow the program receive user input
import java.util.Scanner;
//The class Solution is defined
public class Solution {
//The main method is defined here and signify the beginning of program execution
public static void main(String args[]) {
//Scanner object 'scan' is created to receive user input
Scanner scan = new Scanner(System.in);
//Prompt display to the user to enter size of array
System.out.print("Enter the range of array: ");
//User input is assigned to arraySize
int arraySize = scan.nextInt();
//userArray is initialized with arraySize as its size
int[] userArray = new int[arraySize];
//counter to count number of array element
int count = 0;
//while loop which continue executing till the user finish entering the array element
while (count < arraySize){
System.out.print("Enter each element of the array: ");
userArray[count] = scan.nextInt();
count++;
}
//A blank line is printed for clarity
System.out.println();
//for loop to print each element of the array on straight line
for(int i =0; i <userArray.length; i++){
System.out.print(userArray[i] + " ");
}
//A blank line is printed for clarity
System.out.println();
//for loop is use to reverse the array in-place
for(int i=0; i<userArray.length/2; i++){
int temp = userArray[i];
userArray[i] = userArray[userArray.length -i -1];
userArray[userArray.length -i -1] = temp;
}
//for loop to print each element of the reversed array on straight line
for(int i =0; i <userArray.length; i++){
System.out.print(userArray[i] + " ");
}
}
}
Explanation:
The program is commented to give detailed explanation.
The for-loop use in reversing the array works by first dividing the array into two half and exchanging the first half elements with the second half elements. The element from the first half is assigned to temp variable on each loop, then the element is replaced with the equivalent element from the second half. And the element from the second half is replaced with the value of temp.