AP Computer Science A · Topic 4.5

Informal Code Analysis (Loop Tracing) Practice

Part of Iteration.

Practice questions

10

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

  1. Sample 1difficulty 2/5

    int sum = 0;
    for (int i = 1; i < 5; i++) {
      sum += i;
    }
    System.out.println(sum);

    What is printed?

    • A

      10

      check_circle
    • B

      5

    • C

      14

    • D

      15

    Why

    The condition is i < 5, so i takes values 1, 2, 3, 4 (NOT 5). Sum = 1+2+3+4 = 10. A common off-by-one bug if the author wanted 1..5.

  2. Sample 2difficulty 3/5

    How many iterations does <code>for (int i = 0; i <= 10; i++)</code> perform?

    • A

      10

    • B

      9

    • C

      11

      check_circle
    • D

      12

    Why

    i = 0, 1, 2, ..., 10 → 11 values.

  3. Sample 3difficulty 3/5

    How many times does <code>for (int i = 5; i < 100; i += 5)</code> execute?

    • A

      21

    • B

      18

    • C

      20

    • D

      19

      check_circle

    Why

    i: 5, 10, 15, ..., 95 → 19 values.

  4. Sample 4difficulty 4/5

    String result = "";
    for (int i = 1; i <= 3; i++) {
      for (int j = 1; j <= i; j++) {
        result += "*";
      }
      result += "|";
    }
    System.out.println(result);

    What is printed?

    • A

      <strong>|</strong><em>|</em>***|

    • B

      <em><strong>|</strong>|</em>|

    • C

      <em>|</em>|*|

    • D

      <em>|<strong>|</strong></em>|

      check_circle

    Why

    For i=1: one "<em>", then "|". For i=2: two "</em>", then "|". For i=3: three "<em>", then "|". Result: "</em>|<strong>|</strong>*|".

  5. Sample 5difficulty 4/5

    <code>for (int i = 0; i <= arr.length; i++)</code> (note <code><=</code>) on a length-5 array

    • A

      Compile error

    • B

      Works fine

    • C

      Skips one element

    • D

      Throws ArrayIndexOutOfBoundsException at i=5

      check_circle

    Why

    Valid indices are 0..length-1; <code><=</code> would access index <code>length</code> (out of bounds).