Learn to calculate the average of the given N numbers in Java using three different methods. All methods are different based on how they provide the input to the program.
1. Algorithm for calculating the average
In simple words, to calculate the average of N numbers we have to add all the numbers, and then divide their sum by N.
In pseudo-code, we can list the steps needed in the following manner:
Step 1 : Start Step 2 : sum = 0, i = 0, average = 0, count = 0 Step 3 : i = i + 2 Step 4 : sum = sum + i, count = count + 1 Step 5 : if i <= 10 then go to on step 3, else go to on step 6 Step 6 : average = sum/count Step 7 : Display "average" Step 8 : Stop
2. Program to calculate average of numbers entered by user
We can read the user input using Scanner
class.
import java.util.Scanner; public class CalculateAverage { public static void main(String[] args) { System.out.println("How many numbers do you want to enter?"); Scanner scanner = new Scanner(System.in); //this is number of input values user will provide in console int count = scanner.nextInt(); double[] array = new double[count]; double sum = 0; for (int i = 0; i < array.length; i++) { System.out.print("Enter input number " + (i + 1) + ": "); array[i] = scanner.nextDouble(); } scanner.close(); for (int i = 0; i < array.length; i++) { sum = sum + array[i]; } //Get the average here double average = sum / count; System.out.format("The average is: %.2f", average); } }
Program output:
How many numbers do you want to enter? 5 Enter input number 1: 10.3 Enter input number 2: 20.6 Enter input number 3: 30.9 Enter input number 4: 5 Enter input number 5: 10 The average is: 15.36
3. Program to calculate average of numbers in array
Calculating the average of all numbers in an array is very much similar to the previous program. Here we have an array already populated with numbers.
double[] array = new double[] {1.1, 2.2, 3.3, 4.4, 5.5}; double total = 0; for (int i = 0; i < array.length; i++) { total = total + array[i]; } //Get the average here double average = total / array.length; System.out.format("The average is: %.2f", average);
4. Program to calculate average of numbers in ArrayList
Since Java 8, Stream API has improved the language a lot and has enabled programmers to write complex logic in very less number of lines of code.
To calculate the average of numbers in this list, we can use the average() method from either IntStream
or DoubleStream
classes.
In below example, mapToDouble()
method returns the DoubleStream
. Using the DoubleStream.average() we can easily find the average.
List<Double> list = new ArrayList<>(List.of(1.1, 2.2, 3.3, 4.4, 5.5)); Double averageValue = list.stream() .mapToDouble((x) -> x) .average() .orElse(Double.NaN); System.out.println(averageValue);
Happy Learning !!
Leave a Reply