public class ReverseArray
{
public static void main(String[] args)
{
int[] array = new int [10];
for (int i =0; i< array.length; i++){
array[i] = (int)(100 + Math.random() * 100);
System.out.print(array[i] + ", ");
}
int temp = 0;
for (int i =0; i<array.length; i++){
temp = array;
for (int j = array.length - 1; j<i; j--){
array [i] = array [j];
array[j] = temp;
}
}
System.out.println();
for (int k =0; k< array.length; k++)
System.out.print(array[k] + ", ");
}
}
Thanks for any input!!
for (int j = array.length - 1; j /* Error: ><i */; j--){
You have both a greater than, and a less than sign. for (int i =0; i<array.length; i++){
temp = array;
for (int j = array.length - 1; j>i; j--){
array [i] = array [j];
array[j] = temp;
}
}
Let's say the array has 5 numbers, 1 through 5.
Now, on the first iteration through the loop, the first value gets changed to the last position, and the last position gets changed to the first.
So far so good.
Now, on the next iteration, j becomes 3(second to the last spot of the array).
Now, remember i is still set to zero. Now the first spot in the array becomes the second to the last spot in the array. Then the second to the last spot becomes the old first spot.
I think you are a little confused on the 2 for loops.
With 2 for loops, the inner for loop runs all the way through until false, then the outer loop increments or decrements, then the inner loop runs all the way through again. The pattern continues until both evaluate to false.
while(low < high) {
swap elements
increment low
decrement high
}
int temp;
int low = 0 ;
int high = array.length - 1 ;
while (low < high) {
temp = array[low];
array[low] = array[high];
array[high] = temp;
low++;
high--;
}
This new code worked out great!