0

How would I switch corresponding elements in an array (Ex: First with last, Second with one before last) using a loop. I've worked out the code using a loop, but it doesn't give the desired result in Eclipse.

int[] a = {1, 2, 3, 4, 5};
int k = 0;
int temp = 0;
while(k < a.length)
{
  temp = a[k];
  a[k] = a[a.length - 1 - k];
  a[a.length - 1 - k] = temp;
  k++;
}

Assume that you don't know the values in the array or how long it is.

3 Answers 3

6

You should only loop halfway through the array, i.e. while (k < a.length / 2) -- if you continue beyond that, you'll end up swapping the swapped elements back to their original positions.

Sign up to request clarification or add additional context in comments.

Comments

1
easier way 
for(int i=0,j=a.length-1;i<j;i++,j--)
{
  int temp=a[i];
  a[i]=a[j];
  a[j]=temp;
}

Comments

0

You're iterating over the entire array, which means you end up undoing what you did in the first half of the iteration. Just iterate for half the length of the array (round down). This should work:

int[] a = {1, 2, 3, 4, 5};
int k = 0;
int temp = 0;
while(k < (a.length / 2)) {
temp = a[k];
a[k] = a[a.length - 1 - k];
a[a.length - 1 - k] = temp;
k++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.