Mohan Ram Mohan Ram - 2 months ago 5
Java Question

Sum and average of values in an array

I want to ask how to add the values and find average of values in an array. I have tried searching multiple times, but I could find something that explains how to do all that in simple code that a new programmer such as myself could understand. If someone could tell me how to do it and explain the codes used, that will be great. Thanks in advance :>


At first you have to take an array of numbers. Iterate all the numbers in the array and add the numbers to a variable. Thus after iteration you will get the sum of the numbers. Now divide the sum by count of numbers (which means the size of array). Thus you will get the average.

int[] numbers = {10, 20, 15, 56, 22};
double average;
int sum = 0;

for (int number : numbers) {
    sum += number;

average = sum / (1.0 * numbers.length);
System.out.println("Average = " + average);

You can also iterate in this way:

for (int i = 0; i < numbers.length; i++) {
    sum += numbers[i];