AP Computer Science A · Topic 6.2

Traversing Arrays Practice

Part of Array.

Practice questions

5

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 5 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 1/5

    int[] a = {10, 20, 30};
    for (int x : a) {
      System.out.print(x + " ");
    }

    What is printed?

    • A

      10 20 30

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

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

    • A

      0:x 1:y 2:z

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

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

    • B

      26

      check_circle
    • C

      21

    • D

      16

    Why

    Sum of all elements: 2+5+8+11 = 26.

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

    • B

      ArrayIndexOutOfBoundsException after printing 10, 20, 30, 40

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

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

    • C

      for (int i = arr.length - 1; i >= 0; i--)

      check_circle
    • D

      for (int i = 0; i < arr.length; i++)

    Why

    Indices <code>length-1</code> down to 0.