In: Computer Science
Write a program that does the following:
Generate an array of 20 random integers between -100 and 100.
Compute the average of the elements of the array and find the number of elements which are above the average. For example, if the elements of the array were 5 2 4 1 3 then your program should output
The average is 3.0
There are two elements above the average
Find the smallest element of the array as well as its index in the array, and the second smallest element of the array as well as its index in the array. For example, if the elements of the array were 5 2 4 1 3 then your program should output
The smallest element is 1 and its index is 3
The second smallest element is 2 and its index is 1
must be written in Java
/** * @fileName RandomNumber.java * @author * @since 21/3/17 */ import java.util.Arrays; import java.util.Random; public class RandomNumber { /** * @param arr * @param max * @param min */ public static void generateRandomNumber(int[] arr, int max, int min) { Random rand = new Random(); for (int i = 0; i < arr.length; i++) { arr[i] = rand.nextInt((max - min) + 1) + min; } } /** * @param arr * @return */ public static double average(int[] arr) { double sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } double avg = sum / arr.length; return avg; } /** * @param arr * @return */ public static int getSmallestNumber(int[] arr) { int smallest = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] < smallest) { smallest = arr[i]; } } return smallest; } /** * @param arr * @return */ public static int getSecondSmallestNumber(int[] arr) { int firstSmallest; int secondSmallest; firstSmallest = secondSmallest = Integer.MAX_VALUE; for (int i = 0; i < arr.length; i++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < firstSmallest) { secondSmallest = firstSmallest; firstSmallest = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < secondSmallest && arr[i] != firstSmallest) secondSmallest = arr[i]; } return secondSmallest; } /** * @param arr * @param number * @return */ public static int getIndex(int[] arr, int number) { int index = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] == number) { index = i; break; } } return index; } public static void main(String[] args) { // int arr[] = {5,2, 4, 1,3}; int arr[] = new int[20]; int max = 100, min = -100; generateRandomNumber(arr, max, min); System.out.println("Array : " + Arrays.toString(arr)); System.out.println("Average :" + average(arr)); int smallest = getSmallestNumber(arr); int secondSmallest = getSecondSmallestNumber(arr); System.out.println("The smallest element is " + smallest + " and its index is " + getIndex(arr, smallest)); System.out.println("The second smallest element is " + secondSmallest + " and its index is " + getIndex(arr, secondSmallest)); } }
output: