-1

Possible Duplicate:
How do I reverse an int array in Java?

I need to reverse the order of the given numbers in the array without using a temp.

public class Reverse 
{
    public static void main (String[] args)
    {
        int[] num  = { 12, 34, 50, 67, 88 }, cl, cl2;

        for (i=0; i < a.length; i++)
        {
            cl = a[i];
            cl2 = a[(a.length - 1 )-1];
            System.out.println (cl1 + " " + cl2);
        }
    }
}
7
  • 3
    Print array elements from upper-bound to lower-bound index. Commented Dec 5, 2012 at 3:22
  • Impossible. A register is a "temp", and you need a register just to address the array. Commented Dec 5, 2012 at 3:23
  • @AVD - But how do you index the array without a temp? Commented Dec 5, 2012 at 3:23
  • 1
    Same as stackoverflow.com/questions/2137755/… Commented Dec 5, 2012 at 3:26
  • StackExchange != DoMyHomework. Commented Dec 5, 2012 at 3:29

3 Answers 3

5

Since it only seems that you're printing the values out, you can iterate over your array backwards.

for(int i = a.length - 1; i >= 0; i--) {
    // relevant code here
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was about to add this code fragment. Cool :)
3

you can use Collections#reverse to inline a reverse sort of the integer array,

Collections.reverse(Arrays.asList(num));

1 Comment

... as long as you've already covered Collections prior to this homework assignment ;)
1

The answers given are perfect. But i just added another answer in case if you want to store the reverse array into the original array without using any temp. use this.

public class Reverse 
{
    public static void main (String[] args)
    {
        int[] a = { 12, 34, 50, 67, 88 };
        int i, j;

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.