Rotate Array Elements towards Right Side

How to rotate the given array elements towards right side by 1 position.Given an integer array rotate it to right hand side by 1 position and return modified array.

What is Rotate Operation

Rotate operation is used to shift the elements in array. Given an array of integers and when we rotate array by one position towards right, the last element will come at first position and other elements wil be shifted to left by 1 position each.

Examples:

Input:

array1=[10,20,30,50]

Output After right rotate by 1 position:

array2=[50,10,20,30]

Explanation:

Here we can observe that the last element in array 1 is 50 when rotated by 1 position towards right it got shifted to first position.

Also all other elements got shifted in index position towards right side by 1 index value.

Algorithm

  • Take the input array
  • copy the last element into a new variable.
  • Shift the array elements towards right side by 1 position.
  • At the end copy the last element to first position in output array, that is array2.

JAVA Code

package arrayproblems;
import java.util.*;
class problem8 {
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter the size of array (N)");
		int N= sc.nextInt();
		System.out.println("Enter the " + N +" elements of array");
		int array1[]=new int[N];
		
		for(int i=0;i<N;i++) {		
			array1[i]=sc.nextInt();		
		}
		
		int temp=array1[array1.length-1];
		
		for(int i=array1.length-1;i>=1;i--) {		
			array1[i]=array1[i-1];
		}
		
		array1[0]=temp;
		
		for(int i:array1) {
			System.out.print(i+" ");
		}
	}

}

Watch our video for step by step explanation for above code

Similar Posts

Xoriant off campus coding question and solution

Complete Solution For Rob And Mars Problem In Java

Sasken Technologies off campus coding question

2 thoughts on “Rotate Array Elements towards Right Side”

  1. Pingback: APPSIAN off Campus Coding Question - Is It Actually

  2. Pingback: Accenture off campus coding question - Is It Actually

Leave a Comment

Your email address will not be published. Required fields are marked *