Exercise:
Write a Java Program to Calculate Average Using Arrays.
Click Here to View the Solution!
public class AverageCalculator
{
public static void main(String[] args) {
double[] numArray = { 78.9, 61.3, -32.4, 12.89, 37.8, 98.7 };
double sum = 0.0;
for (double num: numArray) {
sum += num;
}
double average = sum / numArray.length;
System.out.format("The average is: %.2f", average);
}
}
Click Here to View the Output!
The average is: 42.87
Click Here to View the Explanation!
- This program depicts the usage of arrays in calculating average of floating point values.
- In the following code, decimal numbers (floating values) are being stored in an array declared as
numArray ={ 78.9, 61.3, -32.4, 12.89, 37.8, 98.7 }
- The process for calculating average inculcates taking sum of the given numbers in the first place.
- Sum is being calibrated here by employing for-each loop, which takes up values from the array one by one and adds the results to ‘sum’ in each iteration.
- Once the sum is calculated, the resultant value is divided by the number of elements that exist in the array.
- To calculate number of elements in ‘
numArray
’, function ‘numArray.length
’ comes into play. - The value after division is stored in ‘average’ variable, and the result is displayed after being rounded off up to 2 decimal points i.e.
42.87
.