peter
peter

Reputation: 23

Java Shifting the values in an array back one by one

I'm writing a code in Java. I have a question about arrays. I'm trying to shift the values ​​in the array back one by one.

int i;

    int[] a = new int[10];

        for(i = 0; i < 10; i++)                                                                      
            { a[i] = i; }


        for(i = 9; i > 0; i--) 
            { a[i] = a[i - 1]; }
                                                                                                 
       for(i = 0; i < 10; i++) {
       System.out.println("a[" + i +"] => " + a[i]);
    }

Its output is

a[0] => 0
a[1] => 0
a[2] => 1
a[3] => 2
a[4] => 3
a[5] => 4
a[6] => 5
a[7] => 6
a[8] => 7
a[9] => 8

But I want the output to be like this

a[0] => 9     
a[1] => 0
a[2] => 1
a[3] => 2
a[4] => 3
a[5] => 4
a[6] => 5
a[7] => 6
a[8] => 7
a[9] => 8 

what is the simplest way to change a[0] => 0 to a[0] => 9?
Thank you so much for your kindness beforehand.

Upvotes: 2

Views: 86

Answers (2)

Steephen
Steephen

Reputation: 15824

The simplest method is updating the array using index.

array[0] = <new value>

As per your output, there is no shifting happening.

Upvotes: 1

RAZ_Muh_Taz
RAZ_Muh_Taz

Reputation: 4089

You should create a variable that's a copy of the last value of the array. Then set it to your first index of the array AFTER your for loop logic.

int lastNumberInArray = a[a.length - 1];

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

a[0] = lastNumberInArray;

Upvotes: 1

Related Questions