Array: Number of elements greater than average

Question: Write a program that finds the average of contents in an array and counts the number of elements greater than the average

package Array;

/**
 * Created by aarushi on 30/4/21.
 * Q: Write a program that finds the number of items above the average of all items.
 */
import java.util.Scanner;

public class ArrayGreaterThanAverage {

    /*Step 1: Ask user to input size of the array
      Step 2: Ask user to enter elements
      Step 3: Find average of the elements
      Step 4: Compare all the elements to the average and count those greater than the average
     */

    public static void main (String [] args){
        Scanner sc= new Scanner (System.in);
        //Ask user to input array size
        System.out.print("Enter the size of the array: ");
        int arrSize= sc.nextInt();

        int [] array = new int[arrSize];
        int sum=0, count=0;

        //ask user to input array elements
        System.out.println("\nEnter elements of the array: ");
        for (int i=0; i<arrSize; i++){
            array[i]= sc.nextInt();
            sum+=array[i];
        }

        //calculate average
        int avg= sum/arrSize;

        //find number of elements greater than average
        for (int i=0; i<arrSize; i++){
            if(array[i]>avg){
                count++;
            }
        }

        //display average and count
        System.out.println("Average: " + avg);
        System.out.println("Number of elements greater than the average: " + count);

    }

}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close