Contents

Average value of an array (with.Java)

   Jan 8, 2024     1 min read

This is the “Average value of an array” problem.

We’re going to learn about it by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.

Let’s start with the problem

The problem

An array of integers, numbers, is given as a parameter.

Complete the solution function so that it returns the average value of the elements in numbers.

Example input and output

numbersresult
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]5.5
[89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]94.0

My solution to the ### problem

class Solution {
    public double solution(int[] numbers) {
        double answer = 0;
        for(int num : numbers){
            answer += num;
        }
        answer /= numbers.length;
        return answer;
    }
}

Solution

double answer = 0;: initialize the variable answer to 0 to store the resulting value.

for (int num : numbers) : Iterate over each number (num) in the array numbers.

answer += num;: Compute the sum of all numbers by adding each number to answer.

answer /= numbers.length;: Calculate the average by dividing the sum of the numbers by the length of the array (the number of numbers).

return answer;: Returns the calculated average value.