Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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;
over 4 years ago · Santiago Trujillo Report

0

The simplest method is updating the array using index.

array[0] = <new value>

As per your output, there is no shifting happening.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!