Developing Algorithms Using Arrays

AP Computer Science A· difficulty 2/5

public static int countNeg(int[] a) {
    int count = 0;
    for (int x : a) {
        /* missing code */
    }
    return count;
}

Which line correctly replaces /* missing code */ to count negative values?

  • A

    count = x < 0 ? 1 : 0;

  • B

    if (x > 0) count--;

  • C

    if (x < 0) return ++count;

  • D

    if (x < 0) count++;

    check_circle

Explanation

Increment count whenever the current element is negative; returning inside the loop would stop after the first negative, and option D overwrites instead of accumulating.

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

Related questions