AP Computer Science A · Topic 6.3

Enhanced for Loop for Arrays Practice

Part of Array.

Practice questions

6

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 6 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. 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?

    • A

      17

      check_circle
    • B

      16

    • C

      15

    • D

      1

    Why

    The enhanced for-loop visits every element. 5+3+8+1 = 17.

  2. Sample 2difficulty 3/5

    <code>for (int x : arr) sum += x;</code> is equivalent to

    • A

      Sum first element only

    • B

      Index-based for loop summing all elements

      check_circle
    • C

      Sum elements at even indices

    • D

      Compile error

    Why

    Enhanced-for iterates each element in order.

  3. 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?

    • A

      1 2 3

      check_circle
    • 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.

  4. 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

    • D

      Sets local copy x to 0; array unchanged

      check_circle

    Why

    <code>x</code> is a local copy of each element (for primitives); modification doesn't affect array.

  5. 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

    • C

      Cannot modify the array element through the loop variable x

      check_circle
    • 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.