Using a loop and indexed addressing, write code that rotates the members of a 32-bit integer array forward one position. The value at the end of the array must wrap around to the ?rst position. For example, the array [10,20,30,40] would be transformed into [40,10,20,30].

Answer :

Answer:

//begin class definition

public class Rotator{

    //main method to execute the program

    public static void main(String []args){

       

       //create and initialize an array with hypothetical values

       int [] arr =  {10, 20, 30, 40};

       

       //create a new array that will hold the rotated values

       //it should have the same length as the original array

       int [] new_arr = new int[arr.length];

       

       

       //loop through the original array up until the

       //penultimate value which is given by 'arr.length - 1'

      for(int i = 0; i < arr.length - 1; i++ ){

           //at each cycle, put the element of the

           //original array into the new array

           //one index higher than its index in the

           //original array.

          new_arr[i + 1] = arr[i];

       }

       

       //Now put the last element of the original array

       //into the zeroth index of the new array

       new_arr[0] = arr[arr.length - 1];

       

       

       //print out the new array in a nice format

      System.out.print("[ ");

       for(int j = 0; j < new_arr.length;  j++){

           System.out.print(new_arr[j] + " ");

       }

       System.out.print("]");

       

    }

   

   

}

Sample Output:

[ 40 10 20 30 ]

Explanation:

The code above is written in Java. It contains comments explaining important parts of the code.  A sample output has also been provided.

Other Questions