Take the average of some numbers. Show all the numbers that are below average. You can assume that there will not be more than 20 numbers entered. For example: Enter a weight (0 to stop): 1 Enter a weight (0 to stop): 2 Enter a weight (0 to stop): 3 Enter a weight (0 to stop): 4 Enter a weight (0 to stop): 5 Enter a weight (0 to stop): 6 Enter a weight (0 to stop): 7 Enter a weight (0 to stop): 8 Enter a weight (0 to stop): 9 Enter a weight (0 to stop): 10 Enter a weight (0 to stop): 0 The total was 55 The average is 5.5 Here are all the numbers less than the average: 1 2 3 4 5

Respuesta :

Here is code in java.

import java.util.*; // import package

class Main //  creating class

{

public static void main (String[] args) // main method

{

Scanner br=new Scanner(System.in); // scanner class for input

       int []a=new int[20]; // declaring array

       int count=0,x,j; // creating variable

       int sum =0;

       System.out.println("Enter a weight (0 to stop):");

       x=br.nextInt(); // taking input

while(x!=0) // iterating over the loop

       {

           a[count] = x;

           count++;

           System.out.println("Enter a weight (0 to stop):");

           x=br.nextInt();

}

       for( j=0;j<count;j++) // iterating over the loop

       {

       sum+=a[j];

       }

       double avg = sum/(double)count;

       System.out.println("The total is: "+sum);

       System.out.println("The average is: "+avg);

       System.out.println("Here are all the numbers less than the average: ");

     for( j=0;j<count;j++) //  // iterating over the loop

       {

           if(a[j]<avg)

           System.out.print(a[j]+" ");

       }

}

}

Explanation:

First create an object of "Scanner" class to read input from the user.

Create an array of size 20, which store the number given by user.Ask user

to give input and keep the count of number in the variable "count". If user

give input 0 then it will stop taking input.And then calculate sum of all the

input.It will calculate average by dividing the sum with count and print it.

It will compare the all elements of array with average value, if the element

is less than average, it will print that element.

Output:

Enter a weight (0 to stop):

1

Enter a weight (0 to stop):

2

Enter a weight (0 to stop):

3

Enter a weight (0 to stop):

4

Enter a weight (0 to stop):

5

Enter a weight (0 to stop):

6

Enter a weight (0 to stop):

7

Enter a weight (0 to stop):

8

Enter a weight (0 to stop):

9

Enter a weight (0 to stop):

10

Enter a weight (0 to stop):

0

The total is: 55

The average is: 5.5

Here are all the numbers less than the average:

1 2 3 4 5