w3resource

Java: Calculate and print average of the stream of given numbers


Stream Average Calculation

Write a Java program to calculate and print the average (or mean) of the stream of given numbers.

Sample Solution:

Java Code:

import java.util.*;
class solution {   
    // Prints average of a stream of numbers 
    static void streamAvg(float arr[]) 
    { 
        int n = arr.length; 
		float avg = 0; 
        for (int i = 0; i < n; i++)  
        { 
            //avg = getAvg(avg, arr[i], i); 
			avg = (avg * i + arr[i]) / (i + 1);
            System.out.printf("Average of %d numbers is %f \n", 
                                                   i + 1, avg); 
        } 
        return; 
    } 
  
    // Calculate the new average
    static float getAvg(float prev_avg, float x, int n) 
     { 
        return (prev_avg * n + x) / (n + 1); 
     }
  
    public static void main(String[] args) 
     { 
        float arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; 
        streamAvg(arr); 
     } 
}

Sample Output:

 Average of 1 numbers is 10.000000 
Average of 2 numbers is 15.000000 
Average of 3 numbers is 20.000000 
Average of 4 numbers is 25.000000 
Average of 5 numbers is 30.000000 
Average of 6 numbers is 35.000000 
Average of 7 numbers is 40.000000 
Average of 8 numbers is 45.000000 
Average of 9 numbers is 50.000000 
Average of 10 numbers is 55.000000

Flowchart:

Flowchart: Calculate and print average of the stream of given numbers.



For more Practice: Solve these Related Problems:

  • Write a Java program to calculate the average of numbers from a stream using Java 8 collectors.
  • Write a Java program to compute the average of an integer stream in parallel and compare the performance with a sequential stream.
  • Write a Java program to implement a custom average calculation on a stream using reduce and map operations.
  • Write a Java program to filter a stream of numbers before calculating the average using lambda expressions.

Go to:


PREV : Power Without Multiplication or Division.
NEXT : Count Numbers Without 7.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.