The divide by 2 won't work entirely. It will only work if you have an odd number of integers.
For instance:
Give me an integer that would represent the length of an array: 5
Enter 5 value(s)
Value #0:
1
Value #1:
2
Value #2:
3
Value #3:
4
Value #4:
5
Your current array: 1 | 2 | 3 | 4 | 5 |
Your array reversed: 5 | 4 | 3 | 2 | 1 | BUILD SUCCESSFUL (total time: 11 seconds)
Now, if you were to put in an even number integers, let's say 6, this is what would happen:
Give me an integer that would represent the length of an array: 6
Enter 6 value(s)
Value #0:
1
Value #1:
2
Value #2:
3
Value #3:
4
Value #4:
5
Value #5:
6
Your current array: 1 | 2 | 3 | 4 | 5 | 6 |
Your array reversed: 6 | 5 | 3 | 4 | 2 | 1 | BUILD SUCCESSFUL (total time: 5 seconds)
Source code:
/*
Write a program that prompts the user for an integer that would represent the length of an array, 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.
*/
package reversinganarray;
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++;
}
}
}
I happen to be trying to figure this problem out myself...