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

JAVA. Write a loop that sets newScores to oldScores shifted once left, with elem

ID: 3860282 • Letter: J

Question

JAVA. Write a loop that sets newScores to oldScores shifted once left, with element 0 copied to the end. Ex: If oldScores = {10, 20, 30, 40}, then newScores = {20, 30, 40, 10}.

public class StudentScores {
public static void main (String [] args) {
final int SCORES_SIZE = 4;
int[] oldScores = new int[SCORES_SIZE];
int[] newScores = new int[SCORES_SIZE];
int i = 0;

oldScores[0] = 10;
oldScores[1] = 20;
oldScores[2] = 30;
oldScores[3] = 40;

/* Your solution goes here */

for (i = 0; i < SCORES_SIZE; ++i) {
System.out.print(newScores[i] + " ");
}
System.out.println();

return;
}
}

Explanation / Answer

StudentScores.java


public class StudentScores {
   public static void main (String [] args) {
   final int SCORES_SIZE = 4;
   int[] oldScores = new int[SCORES_SIZE];
   int[] newScores = new int[SCORES_SIZE];
   int i = 0;
   oldScores[0] = 10;
   oldScores[1] = 20;
   oldScores[2] = 30;
   oldScores[3] = 40;
   /* Your solution goes here */
   int j = 0;
   for(i=0; i < SCORES_SIZE; i++){
       if(i == SCORES_SIZE - 1){
           j = 0;
       }
       else{
           j = i+1;
      }
       newScores[i] = oldScores[j];
   }

   for (i = 0; i < SCORES_SIZE; ++i) {
   System.out.print(newScores[i] + " ");
   }
   System.out.println();
   return;
   }
   }

Output:

20 30 40 10