In: Computer Science
Programmer defined Function / Arrays: 1.Write a function for printing an array. void print_array (int arr[], int size); 2. Write a function to generate an array of random integers. void random_array (int arr[], int size, int range); The scale of numbers should be 1 to range. 3. Write a function to find the sum of a sequence of number. int sum (int arr[], int size); 4. Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Example: Rotation of the above array by 2 will make array. In your main function, call the above functions: Declare an array of size that input by user. Initialize this array with random values. (task 2) Display this array. (task 1) Display the sum of the numbers in the array. (task 3) Ask user for number of elements to rotate ‘d’. Call the user defined function named ‘rotate’. (task 4) Display the array again.
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Array {
public static void main(String[] args) {
Scanner s = new
Scanner(System.in);
System.out.println("Enter the size
of the array");
int size = s.nextInt();
int arr[] = new int[size];
System.out.println("Enter the range
of randomization for the array");
int range = s.nextInt();
random_array(arr, size,
range);
print_array(arr, size);
int sum = sum(arr, size);
System.out.println("The sum of the
values of the above array is " + sum);
}
static void print_array(int arr[], int size){
for (int i=0; i<size;i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
static void random_array(int arr[], int size, int
range){
int random = 0;
for (int i=0; i<size;
i++){
random =
ThreadLocalRandom.current().nextInt(1, range+1);
arr[i] =
random;
}
}
static int sum (int arr[], int size){
int sum = 0;
for (int i=0; i<size;i++){
sum +=
arr[i];
}
return sum;
}
}
P. S. The description of the fourth function (rotation) is not
clear and the example is incomplete. Please give more details in
comments and I'll work on it :)