Developing Algorithms Using Arrays

AP Computer Science A· difficulty 2/5

public static double avg(int[] a) {
    int total = 0;
    for (int x : a) total += x;
    return /* missing */;
}

Which expression computes the average correctly?

  • A

    a.length / total

  • B

    total / (double) a

  • C

    (double) total / a.length

    check_circle
  • D

    total / a.length

Explanation

Casting total to double forces floating-point division; otherwise integer division would truncate.

Want 10 more like this — adaptive to your weak spots?

Related questions