views:

88

answers:

4

Given an array a and two other int variables, k and temp , write a loop that reverses the elements of the array.

for(k=0;k<a.length-1;k++){
temp=a[k];
a[k]=a[a.length-1-k];
a[a.length-1-k]=temp;
}

This is not working. Any idea why?

+4  A: 

E.g., for a = [0, 1, 2, 3, 4, 5] you'll switch 0 and 5 twice: when i == 0 and when i == 5. This double-switching will put both elements into their original positions: (0, 5) -> (5, 0) -> (0, 5).

Try to make your loop to go through half of array only: so each pair is switched once.

Nikita Rybak
Oh ok that works..thanks!
fprime
IMO when a question is tagged "homework", you shouldn't give that away too easily.
gawi
@gawi Yeah, probably it was better to omit last paragraph. But I was too hasty to post the first answer :)
Nikita Rybak
@Nikita I admit, it's very tempting to do so. For "homework" questions, maybe we should up-vote answers that are more pedagogic and down-vote answers that aren't forcing the student to think or to develop an analytical skill.
gawi
A: 

You are swapping elements from each end of the array... and iterating to the items you've already swapped... is that enough of a hint?

Noel M
+1  A: 

You need to stop your loop at a.length/2 (in the middle).

for(k=0;k<a.length/2;k++)

This should work for odd and even length arrays if this is integer division.

JoshD
Agree. Otherwise the array will be reversed twice to origin.
卢声远 Shengyuan Lu
A: 

You might also want to look at the ArrayUtils.reverse method.

Here is an example using that method.

I know you cannot use it in this assignment. But you should be aware of this and use it whenever possible, say in your assignments, projects.

codaddict