Java program to find the average of given numbers using arrays


You can read data from the user using scanner class.

  • Using the nextInt() method of this class get the number of elements from the user.
  • Create an empty array.
  • Store the elements entered by the user in the array created above.
  • Finally, Add all the elements in the array and divide the sub by the number of elements.

Example

import java.util.Scanner;
public class AverageUsingArrays {
   public static void main(String args[]){

      //Reading total no.of elements
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number of elements/numbers");
      int num = sc.nextInt();

      //Creating an array
      int[] myArray = new int[num];

      //Read numbers from user and store it in an array
      System.out.println("Enter the numbers one by one : ");
      System.out.println("Press Enter button after each number : ");

      for(int i =0; i<num; i++){
         myArray[i] = sc.nextInt();
      }

      //Calculate the average
      double average = 0;
      for(int i =0; i<num; i++){
         average = average + myArray[i];
      }

      average = average/num;
      System.out.println("Average of given numbers :: "+average);
   }
}

Output

Enter the number of elements/numbers
5
Enter the numbers one by one :
Press Enter button after each number :
55
66
55
55
66
Average of given numbers :: 59.4

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 13-Mar-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements