AP Computer Science A · Topic 6.2
Traversing Arrays Practice
Part of Array.
Practice questions
5
Sample questions
5 of 5 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 1/5
int[] a = {10, 20, 30}; for (int x : a) { System.out.print(x + " "); }What is printed?
- Acheck_circle
10 20 30
- B
10 20 30
- C
30 20 10
- D
0 1 2
Why
The for-each loop prints each element followed by a space, in order. Note: a trailing space is included after 30.
- A
Sample 2difficulty 2/5
String[] s = {"x", "y", "z"}; for (int i = 0; i < s.length; i++) { System.out.print(i + ":" + s[i] + " "); }What is printed?
- Acheck_circle
0:x 1:y 2:z
- B
x:0 y:1 z:2
- C
1:x 2:y 3:z
- D
0:x 1:y 2:z
Why
Indices start at 0. Note the trailing space after each printout, including after z.
- A
Sample 3difficulty 2/5
int[] a = {2, 5, 8, 11}; int i = 0; int sum = 0; while (i < a.length) { sum += a[i]; i++; } System.out.println(sum);What is printed?
- A
11
- Bcheck_circle
26
- C
21
- D
16
Why
Sum of all elements: 2+5+8+11 = 26.
- A
Sample 4difficulty 3/5
int[] a = {10, 20, 30, 40}; for (int i = 0; i <= a.length; i++) { System.out.println(a[i]); }What happens?
- A
Compilation error
- Bcheck_circle
ArrayIndexOutOfBoundsException after printing 10, 20, 30, 40
- C
Prints nothing
- D
Prints 10, 20, 30, 40 with no error
Why
The condition i <= a.length is the classic off-by-one bug. After printing all four elements, i=4 and a[4] throws ArrayIndexOutOfBoundsException. The correct condition is i < a.length.
- A
Sample 5difficulty 3/5
To traverse <code>arr</code> from last to first:
- A
for-each
- B
for (int i = arr.length; i > 0; i--)
- Ccheck_circle
for (int i = arr.length - 1; i >= 0; i--)
- D
for (int i = 0; i < arr.length; i++)
Why
Indices <code>length-1</code> down to 0.
- A