Answer:
//To facilitate user input, the Scanner class is imported
import java.util.Scanner;
//The Solution class is being defined
public class Solution {
//The main method is declared here, marking the start of program execution
public static void main(String args[]) {
//A Scanner object named 'scan' is instantiated to gather user input
Scanner scan = new Scanner(System.in);
//User is prompted to specify the size of the array
System.out.print("Enter the range of array: ");
//The user input is stored in arraySize
int arraySize = scan.nextInt();
//Initialization of userArray with the size specified by arraySize
int[] userArray = new int[arraySize];
//A counter is initialized to track the number of elements entered in the array
int count = 0;
//The following while loop will continue until the user finishes inputting the elements of the array
while (count < arraySize){
System.out.print("Enter each element of the array: ");
userArray[count] = scan.nextInt();
count++;
}
//A blank line is outputted for better readability
System.out.println();
//A for loop iterates to print all elements of the array in a single line
for(int i =0; i <userArray.length; i++){
System.out.print(userArray[i] + " ");
}
//Another blank line is printed for clarity
System.out.println();
//A for loop is utilized to reverse the contents of the array
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;
}
//A for loop prints each element of the reversed array in one line
for(int i =0; i <userArray.length; i++){
System.out.print(userArray[i] + " ");
}
}
}
Explanation:
The program is annotated to provide a thorough explanation.
The for-loop responsible for reversing the array operates by splitting the array into two segments and swapping elements from the first segment with those from the second segment. During each loop, an element from the first segment is temporarily stored in temp variable, and then that element is replaced with the corresponding element from the second segment. Subsequently, the element from the second segment is updated with the value held in temp.