0

The instruction is

Implement the method public static double avg(int[][] a), which returns the average of the values stored in a.

So, I guess I have to write

public static double avg(int[][] a) { // two dimensional arrays?
  // some codes
  return a;
}

I don’t understand the sentence “which returns the average of the values stored in a”. When I don’t even know the values stored in a, how can I get the average?

1
  • 5
    Add up all the values and calculate an average... Commented Sep 10, 2015 at 5:43

3 Answers 3

4

The function takes a 2d array as an argument. I believe you are supposed to do 2 for loops over a and sum each item and then divide by number of total items in the end (average). Then return your double (average) variable, not return a as your code shows.

Sign up to request clarification or add additional context in comments.

Comments

2

yes I agree with David, you will need 2 nested for loops to add all the values and return it.

something like...

public static double avg(int [][] a)
    {
        double sum = 0;
        int total = 0;
        for(int i = 0; i < a.length; i++){
            total += a[i].length;
            for (int j = 0; j < a[i].length; j++){
                sum+=a[i][j];
            }
        }
        return sum/total;
    }

and then divide the sum by number of elements.

Comments

1

With a double array you have to walkthrough all the items. The program will count the amount of values in the array and sum all values. To get the average you have to devide the total by the amount of values.

public static double avg(int[][] a)
{
    int amountOfValues = 0;
    int total = 0;
    for(int y = 0; y < a.length; y++)
    {
        for(int x = 0; x < a[y].length; x++)
        {
            total += a[y][x];
            amountOfValues++;
        }
    }
    return (double)(total)/(double)(amountOfValues);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.