Java Array find array element above average

Question

The problem is to write a program that finds the number of items above the average of all items.

  • read 100 numbers
  • get the average of these numbers
  • find the number of the items greater than the average.
  • let the user enter the number of input

public class Main {
  public static void main(String[] args) {
    java.util.Scanner input = new java.util.Scanner(System.in);
    System.out.print("Enter the number of items: ");
    int n = input.nextInt();
    double[] numbers = new double[n];
    double sum = 0;

    //your code here
  }/*from   w ww  .j a  va  2 s .c om*/
}




public class Main {
  public static void main(String[] args) {
    java.util.Scanner input = new java.util.Scanner(System.in);
    System.out.print("Enter the number of items: ");
    int n = input.nextInt();
    double[] numbers = new double[n];
    double sum = 0;

    System.out.print("Enter the numbers: ");
    for (int i = 0; i < n; i++) {
      numbers[i] = input.nextDouble();
      sum += numbers[i];
    }
    
    double average = sum / n;

    int count = 0; // The numbers of elements above average
    for (int i = 0; i < n; i++) 
      if (numbers[i] > average)
        count++;

    System.out.println("Average is " + average);
    System.out.println("Number of elements above the average is "
      + count);
  }
}



PreviousNext

Related