In this example , we will learn how to find the average of numbers using array. This will get you familiar with the basic syntax and requirements of a Java program.
Example 1: Program finds the average of specified array elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class JavaExample { public static void main(String[] args) { double[] array = {10, 20.50, 30.50, 40, 40.55}; double sum = 0; //print array elements System.out.print("Numbers:"); for(int i=0; i<array.length; i++){ System.out.print(", "+array[i]); } for(int i=0; i<array.length; i++){ sum = sum + array[i]; } double average = sum / array.length; System.out.format("\nThe AVERAGE IS: %.3f \n", average); //%.3f formats as xx.xxx } } |
Output:
1 2 3 4 | Numbers:, 10.0, 20.5, 30.5, 40.0, 40.55 The AVERAGE IS: 28,310 |
Example 2: Program takes the value of n (number of elements) and the numbers provided by user and finds the average of them using array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import java.util.Scanner; public class JavaExample { public static void main(String[] args) { double[] array; double sum = 0; System.out.println("How many numbers you want to enter?"); Scanner scanner = new Scanner(System.in); int count = scanner.nextInt(); array = new double[count]; for(int i=0; i<array.length; i++){ System.out.print("Enter Element No."+(i+1)+": "); array[i] = scanner.nextDouble(); //add numbers to sum sum = sum + array[i]; } scanner.close(); double average = sum / array.length; System.out.format("\nThe AVERAGE IS: %.3f \n", average); //%.3f formats as xx.xxx } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 | How many numbers you want to enter? 5 Enter Element No.1: 20 Enter Element No.2: 30 Enter Element No.3: 40 Enter Element No.4: 50 Enter Element No.5: 60 The AVERAGE IS: 40,000 |