for Loops

AP Computer Science A· difficulty 3/5

public static void doubleAll(int[] a) {
    for (int x : a) {
        x = x * 2;
    }
}

What is wrong with this method?

  • A

    The loop should use *= instead of =

  • B

    Nothing is wrong

  • C

    The method needs a return statement

  • D

    The for-each variable is a copy; the array is not modified

    check_circle

Explanation

The enhanced for-loop variable x is a copy of each element. Assigning to x does not change the array; an indexed for-loop is required to mutate elements.

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

Related questions