Questions: Array Indexing and Bounds

5 questions to test your understanding

Score: 0 / 5
Question 1 Multiple Choice

A programmer writes a loop that runs while i <= arr.length and accesses arr[i] on each iteration. The array has 5 elements. What error will occur?

AA syntax error because the comparison operator is wrong for array iteration
BAn out-of-bounds error because when i equals arr.length (5), arr[5] doesn't exist — the last valid index is 4
CNo error; arr.length is always a valid index in this context
DA logic error because the loop runs one too few times
Question 2 Multiple Choice

In a zero-based indexed array nums = [10, 20, 30, 40, 50], what does nums[nums.length - 1] return?

A40 (the second-to-last element)
B50 (the last element)
CAn out-of-bounds error
D10 (the first element)
Question 3 True / False

In a zero-based indexed array of length 8, the valid indices are 0 through 7.

TTrue
FFalse
Question 4 True / False

In most programming languages, array indices start at 1, so an array of 5 elements has valid indices 1 through 5.

TTrue
FFalse
Question 5 Short Answer

Explain why the last valid index of an array is length − 1 rather than length. Use a concrete example.

Think about your answer, then reveal below.