Unit 2 Cycle 2 Day 21

Unit 2, Section 2.13 - Cycle 2
Day 21 Advanced Practice - Harder Difficulty
Focus: Debugging Off-by-One Errors

Practice Question

A programmer wants to print all elements in an array. Consider the following code segment:
int[] arr = {5, 10, 15, 20, 25};
for (int i = 0; i <= arr.length; i++) {
    System.out.println(arr[i]);
}
Which of the following best describes the result of executing this code?
Why This Answer?

The correct answer is C) The code causes an ArrayIndexOutOfBoundsException

This is a classic off-by-one error. The array has 5 elements with valid indices 0, 1, 2, 3, 4.

The loop condition i <= arr.length is WRONG because:

  • arr.length = 5
  • The loop runs with i = 0, 1, 2, 3, 4, and then 5
  • When i = 5, the code tries to access arr[5], which doesn't exist
  • This throws an ArrayIndexOutOfBoundsException

The correct loop condition should be: i < arr.length (without the equals sign)

Why Not the Others?

A) Prints all 5 elements correctly - This would require the condition i < arr.length, not i <= arr.length.

B) Prints only the first 4 elements - This would happen if the condition was i < arr.length - 1, which would stop at index 3.

D) Prints 6 elements including duplicate - Arrays have fixed size and cannot print elements that don't exist without throwing an exception.

Common Mistake
Watch Out!

Off-by-one errors are one of the most common bugs in programming. Remember: array indices go from 0 to length-1, NOT 0 to length. The loop condition should almost always be i < arr.length, not i <= arr.length. The exception is when you're working with 1-indexed counting (like row numbers), not array indices.

AP Exam Tip

On the AP exam, carefully check loop bounds when working with arrays. A common trap is using <= when you should use <. If you see arr.length in a loop condition, immediately verify whether the code will try to access an invalid index. Array indices are ALWAYS 0 to length-1.

Keep Practicing!

Cycle 2 questions prepare you for the hardest AP CSA exam questions.

Study Games Practice FRQs
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.