AP Computer Science A · Topic 6.3
Enhanced for Loop for Arrays Practice
Part of Array.
Practice questions
6
Sample questions
5 of 6 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
int[] a = {5, 3, 8, 1}; int total = 0; for (int x : a) { total += x; } System.out.println(total);What is printed?
- Acheck_circle
17
- B
16
- C
15
- D
1
Why
The enhanced for-loop visits every element. 5+3+8+1 = 17.
- A
Sample 2difficulty 3/5
<code>for (int x : arr) sum += x;</code> is equivalent to
- A
Sum first element only
- Bcheck_circle
Index-based for loop summing all elements
- C
Sum elements at even indices
- D
Compile error
Why
Enhanced-for iterates each element in order.
- A
Sample 3difficulty 3/5
int[] a = {1, 2, 3}; for (int x : a) { x = x * 2; } System.out.println(a[0] + " " + a[1] + " " + a[2]);What is printed?
- Acheck_circle
1 2 3
- B
2 4 6
- C
0 0 0
- D
Compilation error
Why
The for-each loop variable x is a copy of each element. Reassigning x does not modify the underlying array. To modify, you must use a standard for-loop with an index.
- A
Sample 4difficulty 4/5
Inside <code>for (int x : arr) x = 0;</code>
- A
Sets all array elements to 0
- B
Throws exception
- C
Compile error
- Dcheck_circle
Sets local copy x to 0; array unchanged
Why
<code>x</code> is a local copy of each element (for primitives); modification doesn't affect array.
- A
Sample 5difficulty 4/5
The enhanced for loop <code>for (int x : arr) { ... }</code>
- A
Iterates in reverse order by default
- B
Cannot be used with arrays — only ArrayList
- Ccheck_circle
Cannot modify the array element through the loop variable x
- D
Allows modification by assigning to x
Why
<code>x</code> is a copy of arr[i]. Reassigning x has no effect on arr. To modify arr in place, use the indexed for loop.
- A