class Exercise3
{
public static void main ( String[] args )
{
int[] val = {0, 1, 2, 3};
int temp;
System.out.println( "Original Array: "
+ val[0] + " " + val[1] + " " + val[2] + " " + val[3] );
for(int j = 0; j<(val.length/2); j++){ //length is 4 so 4/2 = 2 which is true and y do i have to divide the length by 2? i deleted the /2 and then it prints the same array but the length of an array is 4 which is less than 0 so y do i have to divide it by 2?
temp = val[j]; //assign val[] to temp
val[j] = val[val.length-1-j]; //val[0] = val[4-1-0] which is 3 for the first iteration of the for loop.
val[val.length-1-j] = temp; // i can't understand this assignment statement temp is holding the values of array }
System.out.println( "Reversed Array: "
+ val[0] + " " + val[1] + " " + val[2] + " " + val[3] );
}
}
Message was edited by: int[] reverse = new int[4];
reverse[0] = val[3];
........
System.out.println(The reverse array " + reverse[0] + "...");
But since i had to use that temp. i can't figure it out so rather than wasting your guys time i searched it on google and try to see if i can understand the logic behind but did not i know exactly what you saying i could have done itAnd I think you might try that and put it into a for loop and see if you see anything. It might explain about the other.
easily by creating another array;
int[] a = // array with two ints
// swap the two values
int temp = a[0];
a[0] = a[1];
a[1] = temp;
You see how we can copy one value directly but we need one temp variable to hold the other value while we swap? It's reversing the array "in place". So to do thisThat is what my whole question was y do we have to stop at the midpoint? nvm. i will try to write this code in a different way lets see if i can get successful which i know i will and i will post back. i was just getting confused with that midpoint thing.
you take one element (the first or last) and swap it
with the other. You keep doing this until you get to
the mid way point of the array. (Can you think why
you should stop at the midway point?)
I thought your question was about the temp variable.It's reversing the array "in place". So to do thisit
you take one element (the first or last) and swapwith the other. You keep doing this until you gettothe mid way point of the array. (Can you think whyhat is what my whole question was y do we have to
you should stop at the midway point?)
stop at the midpoint?
got it we had to stop at the midpoint because totalI don't know what you mean here. Did you look at my example?
length is 4 but the array index is 3(0,1,2,3).