I Also need helpp on this Reversing an Array Write a program that prompts the us
ID: 3773580 • Letter: I
Question
I Also need helpp on this Reversing an Array Write a program 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.
import java.util.*;
import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args)
{
int numbers=0;
int temp;
int totalsum=0;
Scanner scan = new Scanner(System.in);
int[] integers = new int [5];
System.out.print(" Please enter a numbers that you want to reverse");
numbers= scan.nextInt();
for(int i=0; i<integers.length; i++)
{
System.out.print("Enter amount of integers " +i+ " :");
integers[i] = scan.nextInt();
totalsum=totalsum + integers[i];
}
System.out.print(" The totalsum of integers = " + totalsum);
System.out.print("The integers in reverse order " + " are:");
//print the numbers in the reverse order
for(int i = integers.length-1; i >= 0; i--)
{
System.out.print(integers[i] + " ");
System.out.println();
}
}
}
Explanation / Answer
import java.util.Scanner;
public class ReversinganArray
{
public static void main(String[] args) {
int i = 0;
Scanner input = new Scanner(System.in);
System.out.print("Give me an integer that would represent the length of an array: ");
int integer = input.nextInt();
int[] test = new int[integer];
System.out.println("Enter " + integer + " " + "value(s)");
while (i < integer) {
System.out.println("Value #" + i + ": ");
test[i] = input.nextInt();
i++;
}
System.out.print("Your current array: ");
i = 0;
while (i < integer) {
System.out.print(test[i] + " | ");
i++;
}
i = 0;
while (i <= integer / 2) {
int temp = test[i]; //a = b
test[i] = test[(integer - i - 1)]; //b = c
test[(integer - i - 1)] = temp;// c = a
i++;
}
System.out.println("");
System.out.print("Your array reversed: ");
i = 0;
while (i <= integer - 1) {
System.out.print(test[i] + " | ");
i++;
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.