Arrays
Java Program to Calculate Average Using Arrays
A Java program to calculate the average of numbers using an array.
Problem Description
Write a Java program to calculate the average value of array elements.
Code
public class AverageArray {
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.69Explanation
- Enhanced For Loop: Iterates through each element of the array.
- Sum: Accumulates the sum of all elements.
- Average: Divides the sum by the number of elements (
numArray.length).
Java Program to Work with Arrays - Operations and Examples
Learn essential array operations in Java including initialization, searching, sorting, and manipulation with comprehensive examples and explanations.
Java Program to Find Largest Element of an Array
A Java program to find the largest element in an array.
