Question

Write a JAVA program that rotates a 1-dimensional by 2 elements. For example [1,2,3,4,5,6] rotated by...

Write a JAVA program that rotates a 1-dimensional by 2 elements. For example [1,2,3,4,5,6] rotated by two becomes [3,4,5,6,1,2].

0 0
Add a comment Improve this question Transcribed image text
Answer #1

File Name:

LeftRotatoin.java

Program:

import java.util.Scanner;
class LeftRotation
{
   public static void main(String[] args) {

       // Declaring a Scanner variable for taking input
       Scanner in = new Scanner(System.in);
       // Taking the no.of elements of the array and storing
       // it in variable n.
       System.out.println("Enter no.of values");
       int n=in.nextInt();

       // Taking the elements of the Array and storing it in the
       // array arr.
       System.out.println("Enter numbers");
       int[] arr = new int[n];
       for(int i=0; i<n; i++)
       {
           arr[i] = in.nextInt();
       }

       // Printing the array that we've taken.
       System.out.println("\nArray that you've entered:");
       for(int i=0; i<n; i++)
       {
           System.out.print(arr[i]+" ");
       }  

       // Create a new array to store the resulting values.
       int[] result = new int[n];

       // If we rotate an array of lenth "n" by "r" positions,
       // then the values at an index "i" will be moved to an index
       // position which is equal to (i-r+n)%n which means that,
       // "i" is moved to "r" places left and then, since, we have to
       // neutralize the negative sign (Which might come) we
      // are adding "n" and since, the values should be in
      // range 0...n-1, we are finding modulus of the obtained
      // number (i-r+n) with n. Thus making the new index in range of the 0...n-1

       //here r is 2
       for(int i=0; i<n; i++)
       {
           // you can replace 2 with whatever integer
           // and this rotates the array that number times.
           result[(i-2+n)%n] = arr[i];
       }

       // Printing the array after rotation.
       System.out.println("\n\nAfter Rotaion: ");
       for(int i=0; i<n; i++)
       {
           System.out.print(result[i]+" ");
       }
   }
}

Output:

Please appreciate solution if you like it,

feel free to ask doubts in comment section.

Add a comment
Know the answer?
Add Answer to:
Write a JAVA program that rotates a 1-dimensional by 2 elements. For example [1,2,3,4,5,6] rotated by...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT