AP Computer Science A · Topic 4.4

Nested Iteration Practice

Part of Iteration.

Practice questions

18

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

  1. Sample 1difficulty 3/5

    for (int i = 0; i < 3; i++) {
        for (int i = 0; i < 3; i++) {
            System.out.println("x");
        }
    }

    What is wrong?

    • A

      Compile-time inference fails

    • B

      Nothing is wrong

    • C

      Both loops share i and run nine times correctly

    • D

      Inner loop redeclares i; that variable is already in the enclosing scope

      check_circle

    Why

    Java disallows declaring a variable with the same name as one already in an enclosing block. Rename the inner variable, e.g., j.

  2. Sample 2difficulty 3/5

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

    What is printed?

    • A

      18

      check_circle
    • B

      6

    • C

      9

    • D

      27

    Why

    Inner loop sums 1+2+3 = 6. Outer loop runs 3 times, so total = 6 * 3 = 18.

  3. Sample 3difficulty 3/5

    public static int run() {
        int s = 0;
        for (int i = 1; i <= 3; i++) {
            for (int j = i; j <= 3; j++) {
                s += j;
            }
        }
        return s;
    }
    // Call: System.out.println(run());

    What is printed?

    • A

      18

    • B

      12

    • C

      9

    • D

      14

      check_circle

    Why

    i=1: j=1,2,3 -> 6. i=2: j=2,3 -> 5. i=3: j=3 -> 3. Total = 6 + 5 + 3 = 14.

  4. Sample 4difficulty 3/5

    int count = 0;
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 4; j++) {
        count++;
      }
    }
    System.out.println(count);

    What is printed?

    • A

      7

    • B

      12

      check_circle
    • C

      16

    • D

      9

    Why

    Outer loop runs 3 times, inner loop runs 4 times each. Total iterations = 3 * 4 = 12.

  5. Sample 5difficulty 3/5

    public static int run() {
        int s = 0;
        for (int i = 0; i < 5; i++) {
            if (i == 3) continue;
            s += i;
        }
        return s;
    }
    // Call: System.out.println(run());

    What is printed?

    • A

      7

      check_circle
    • B

      8

    • C

      10

    • D

      6

    Why

    Sum 0+1+2+4 = 7 (skipping 3).