Java How To Find The Average Of 10 Numbers Using A While Loop

Here's a Java example of how to find the average of 10 randomly generated numbers using a while loop:


import java.util.Random;

public class AverageCalculator {
    public static void main(String[] args) {
        int count = 0;     // Initialize count to 0
        double sum = 0.0;  // Initialize sum to 0.0
        Random random = new Random();

        // Use a while loop to generate and sum 10 random numbers
        while (count < 10) {
            double number = random.nextDouble() * 100; // Generate a random number between 0 and 100
            System.out.println("Generated random number: " + number);
            sum += number; // Add the random number to the sum
            count++;      // Increment the count
        }

        // Calculate the average
        double average = sum / 10;

        // Display the average
        System.out.println("The average of the 10 random numbers is: " + average);
    }
}

In this program, we're using a while loop to generate 10 random numbers between 0 and 100, calculate their average, and display the result. The Random class is used to generate random numbers, and the average is calculated in the same way as in the previous examples.



You May Interest

How Will You Handle InterruptedException in Java ?

What is the Difference Between Fail-fast and Fail-safe Iterator i ...

What is the Use of Jsp:useBean in JSP ?

What is the Difference Between Array and ArrayList in Java ?

What are the Advantages of Multithreading in Java ?