Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help trying to write a java program for my begining java class. we are cu

ID: 3691525 • Letter: I

Question

I need help trying to write a java program for my begining java class. we are currently learning arrays in my class and I am suppose to write a program that shifts my array elements to the right. I have started to write the program but it does not work. I get a different output. Can someone help me and tell me where my mistake is? here is my code and my output is

9 4 4 4 4 when I want it to be 9 4 3 1 2 8:

public class ShiftsRight
{
public static void main(String[] args)
{
int [] a = {4, 3, 1, 2, 8 ,9};
  
int temp = a[5];
System.out.print(temp + " ");
  
for( int i = 1; i < a.length - 1; i++)
{
a[ i ] = a[ i-1];
System.out.print( a[ i ] + " ");
}
}
}

Explanation / Answer

//The mistake is that when you are assing a[i] = a[i-1] the previous value of a[i] is lost. For example in the loop first you assign a[1]=a[0] so a[1] now becomes 4. In the next iteration you make a[2]=a[1], but now the vlalue of a[1] is 4. So a[2] also becomes 4.

public class ShiftsRight
{
   public static void main(String[] args)
   {
       int [] a = {4, 3, 1, 2, 8 ,9};

       int temp = a[5],prev;
       for( int i = 0; i < a.length; i++)
       {
           prev = a[i];
           a[ i ] = temp;
           temp = prev;
       }
       for( int i = 0; i < a.length; i++)
       {
           System.out.print(a[i]+" ");
       }
       System.out.println("");
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote