Write a program in Java that prompts the user for an integer, then asks the user
ID: 653330 • Letter: W
Question
Write a program in Java that prompts the user for an integer, then asks the user to enter that many values. Store these values in an array and print the array. Then reverse the array elements so that the first element becomes the last element, the second element becomes the second to last element, and so on, with the old last element now first. Do not just reverse the order in
which they are printed; actually change the way they are stored in the array. Do not create a second array; just rearrange the elements within the array you have. (Hint: Swap elements that need to change places.) When the elements have been reversed, print the array again
Explanation / Answer
import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args) {
int size, temp;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the size of your array: ");
size = scan.nextInt();
int[] myArray = new int[size];
// input array of ints
for(int i = 0; i< myArray.length; i++){
System.out.print("Enter number " + i+": ");
myArray[i] = scan.nextInt();
}
// print original array
printArray(myArray);
//reverse elements in array using swap technique
for(int j = 0; j<(myArray.length/2); j++){
temp = myArray[j];
myArray[j] = myArray[myArray.length-1-j];
myArray[myArray.length-1-j] = temp;
}
// print reversed array
printArray(myArray);
}
// printing an int array
public static void printArray(int[] a){
for(int i =0; i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.