for Loops

AP Computer Science A· difficulty 2/5

int sum = 0;
for (int i = 0; i < a.length; i++) {
    sum += a[0];
}

What is the bug?

  • A

    sum should be initialized to 1

  • B

    Loop should run a.length+1 times

  • C

    Nothing is wrong

  • D

    a[0] should be a[i] to sum every element

    check_circle

Explanation

Always indexing a[0] adds the first element repeatedly. Use a[i] to access the current element.

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

Related questions