0% found this document useful (0 votes)
3 views3 pages

www_programiz_com_java_programming_examples_average_arrays

The document provides a Java program that calculates the average of floating-point numbers stored in an array. It demonstrates the use of a for-each loop to sum the elements and then computes the average by dividing the sum by the total count of elements. The result is printed with two decimal points using the format() function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

www_programiz_com_java_programming_examples_average_arrays

The document provides a Java program that calculates the average of floating-point numbers stored in an array. It demonstrates the use of a for-each loop to sum the elements and then computes the average by dividing the sum by the total count of elements. The result is printed with two decimal points using the format() function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Java Program to Calculate Average

Using Arrays
To understand this example, you should have the knowledge of the following Java
programming topics:

Java Arrays

Java for-each Loop

Example: Program to Calculate Average Using Arrays

public class Average {

public static void main(String[] args) {


double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 };
double sum = 0.0;

for (double num: numArray) {


sum += num;
}

double average = sum / numArray.length;


System.out.format("The average is: %.2f", average);
}
}

Output

The average is: 27.69

In the above program, the numArray stores the floating-point values whose average
is to be found.

Then, to calculate the average , we need to first calculate the sum of all elements in
the array. This is done using a for-each loop in Java.

Finally, we calculate the average by the formula:

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
average = sum of numbers / total count

In this case, the total count is given by numArray.length .

Finally, we print the average using format() function so that we limit the decimal
points to only 2 using "%.2f"

Did you find this article helpful?

Our premium learning platform, created with over a decade of


experience.

Try Programiz PRO

Related Examples

Java Example

Calculate Standard Deviation

Java Example

Find Largest Element of an Array

Java Example

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Calculate the Power of a Number

Java Example

convert double type variables to string

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF

You might also like