JAVA Project Problem : Write a program that allows users to input an integer for
ID: 3837973 • Letter: J
Question
JAVA Project
Problem :
Write a program that allows users to input an integer for the size of an array. (use malloc() ) Randomly generate an integer for each element of the array. Next, create function to rotate the array . Rotation of the array means that each element is shifted right or left by one index, and the last element of the array is also moved to the first place.
For example:
Enter the number of slots needs in the array: 8
This is element of your array: 91 57 18 96 16 49 31 83
Which direction to shift R/L : R
How many times: 2
This is element of your array: 31 83 91 57 18 96 16 49
For example:
Enter the number of slots needs in the array: 3
This is element of your array: 31 83 91
Which direction to shift R/L : L
How many times: 2
This is element of your array: 91 31 83
Explanation / Answer
Program:-
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of slots needs in the array: ");
int size=sc.nextInt();
int arr[] = new int[size];
for(int i=0;i<size;i++){
arr[i] = (int )(Math.random() * 100 + 1);
}
System.out.println("This is element of your array:");
for(int i=0;i<size;i++){
System.out.print(arr[i]+" ");
}
System.out.println("Which direction to shift R/L :");
String ch=sc.next();
System.out.println("How many times: ");
int time=sc.nextInt();
if(ch.equals("R") || ch.equals("r")){
rightRotateArray(arr,time);
}
else if(ch.equals("L") || ch.equals("l")){
leftRotateArray(arr,time);
}
}
//This method is used to shift a integer in right direction by number
//of times entered by user.
public static void rightRotateArray(int arr[],int t){
for (int i = 0; i < t; i++) {
for (int j = arr.length - 1; j > 0; j--) {
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
System.out.println("This is element of your array:");
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
//This method is used to shift a integer in left direction by number
//of times entered by user.
public static void leftRotateArray(int arr[],int t){
for (int i = 0; i < t; i++) {
for (int j = 0; j < arr.length-1; j++) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}}
System.out.println("This is element of your array:");
for(int j=0;j<arr.length;j++){
System.out.print(arr[j]+" ");
}
}
}
Output:-
Enter the number of slots needs in the array:
8
This is element of your array:
90 78 17 43 51 27 82 45 Which direction to shift R/L :
l
How many times:
2
This is element of your array:
17 43 51 27 82 45 90 78
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.