w3resource

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

Java Math Exercises: Exercise-17 with Solution

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.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to calculate power of a number without using multiplication and division operators
Next: Write a Java program to count the numbers without digit 7, from 1 to a given number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/math/java-math-exercise-17.php