Java program to find average of n numbers

Let’s learn java program to find average of n numbers.

Java program to find average of n numbers

In program to find average of n numbers first create integer variable num and set count equal to 1. Next create variables ‘a’, average and total = 0 of type float.

In the while loop check count is less than or equal to num. Then total += a and count = count + 1. Now set average = total / num. Lastly print average entered by user. Here’s program to find average of n numbers.

import java.util.Scanner;
public class FindAverageOfNNumbers
{
   public static void main(String[] args) 
   {
      int num, count = 1;   
      float a, average, total = 0;   
      Scanner sc = new Scanner(System.in);     
      System.out.println("Please enter n numbers: ");  
      num = sc.nextInt();  
      while(count <= num)
      {   
         System.out.println(count + " number: ");  
         a = sc.nextInt();
         total += a;
         ++count;   
      }
      average = total / num;   
      System.out.println("Average is: " + average);
      sc.close();
   }
}


Output:

Please enter n numbers: 6
1 number: 6
2 number: 9
3 number: 9
4 number: 9
5 number: 5
6 number: 9
Average is: 7.8333335