In: Computer Science
For example, if the 10 random numbers are
44 61 98 45 45 17 63 24 9 95
The method should returns an array which contains 61 98 63 95
In the main method, make up an array size, call the method, and display the numbers above the average
Program:
import java.util.*;
public class Main
{
public static ArrayList<Integer> generateRandom(int n) {
int array[] = new int[n]; // Initializing array with the size of n
// Array list to store the elements which are greater than average of array elements
ArrayList<Integer> output_array = new ArrayList<Integer>();
int sum = 0, average;
// Loop iterates n number of times to generate random numbers
for (int i=0; i<n; i++) {
Random rand = new Random();
// Generate random integers in range 0 to 100 and insert into array
array[i] = rand.nextInt(101);
// sum of array elements
sum += array[i];
}
// average of array elements
average = sum/n;
// Loop will find elements which are greater than average
// and add it to ArrayList
for (int i=0;i<n;i++) {
if (array[i] > average) {
output_array.add(array[i]);
}
}
// Printing randomly generated array
System.out.println("Random generated array : ");
for (int i = 0; i < n; i++)
System.out.print(array[i] + " ");
System.out.println();
// Returns array with elements greater than average
return(output_array);
}
public static void main(String[] args) {
int n = 10; // Size of an array
// Will have the array elements which are greater than average of array elements
ArrayList<Integer> final_array = generateRandom(n);
// Printing output
System.out.println("Output Array : ");
for (int i = 0; i < final_array.size(); i++)
System.out.print(final_array.get(i) + " ");
}
}
Output: