raikkonen
raikkonen

Reputation: 13

Moving value from end of int array to the beginning in Java

I have an array of type int:

array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5

I want to take the value at the end, and bring it the beginning and shunt the rest of the elements to the right, so my output will look like: 5, 1, 2, 3, 4

I've considered using an ArrayList, but the assignment seems to want me to just use a primitive array.

Thanks

Upvotes: 0

Views: 2091

Answers (3)

alex2410
alex2410

Reputation: 10994

You can try next:

    int arr[] = new int[]{1,2,3,4,5};
    int val = arr[arr.length-1];
    System.arraycopy(arr, 0, arr, 1, arr.length-1);
    arr[0] = val;

Upvotes: 0

Kshitij Kulshrestha
Kshitij Kulshrestha

Reputation: 2072

Here the code, try this

public class arrayformat {

    public static void main(String[] s)
    {
                int[] array = {1,2,3,4,5};


                int temp = array[4];

                for(int i=array.length-1;i>0;i--)
                {
                    array[i]=array[i-1];
                }

                array[0]= temp;

                for(int i=0;i<array.length;i++)
                {
                    System.out.println(array[i]);
                }

    }
}

Upvotes: 1

vkluge
vkluge

Reputation: 324

You wont need an ArrayList or a LinkedList to achieve that. I'm not going to give you a full solution but try to think about what you know about arrays and what you want to achieve (which value should be placed where (try to work with the array's index)). If you dont have to do an inplace reversion it can be very helpful to create a second array to work with. Check out http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html for a introduction to java arrays.

Upvotes: 0

Related Questions