In: Computer Science
Write a C++ program that will take and validates from the user an integer n between 1 and 4. The program will then continue by taking 5 characters from the user. The program will ask the user whether he needs to rotate the characters to the left or to the right. If the user enters a wrong answer, the program will do a rotation to the right. Depending on the answer, the program will rotate the characters "n" times and displays the result on the screen. The program should contain 2 loops. Example 1: The user will enter a value n=3, the characters A B C D E, and rotation to the left. The program will then display DEABC. Example 2: The user will enter a value n=3, the characters A B C D E, and rotation to the right. The program will then display CDEAB.
import java.util.*;
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char[] ch = new char[5];
for(int i=0;i<5;i++){
ch[i] = sc.next().charAt(0);
}
System.out.print("Rotate left or right : ");
String rotate = sc.next();
if(rotate.equals("right")){
System.out.println("Rotated List : ");
for(int i=0;i<5;i++){
System.out.print(ch[(i+n-1)%5] + " ");
}
}
else if(rotate.equals("left")){
System.out.print("Rotated List : ")
for(int i=0;i<5;i++){
System.out.print(ch[(i+n)%5] + " ");
}
}
}
}
Drop a comment for any clarification or update, I would love to assist you.