AP Computer Science A · Topic 4.2

for Loops Practice

Part of Iteration.

Practice questions

32

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

  1. Sample 1difficulty 2/5

    int count = 0;
    for (int i = 1; i <= 20; i++) {
      if (i % 2 == 1) {
        count++;
      }
    }
    System.out.println(count);

    What is printed?

    • A

      10

      check_circle
    • B

      11

    • C

      20

    • D

      9

    Why

    Odd numbers from 1 to 20 are 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 — exactly 10 numbers.

  2. Sample 2difficulty 2/5

    int i = 5;
    while (i > 0) {
      System.out.print(i);
      i--;
    }

    What is printed?

    • A

      12345

    • B

      54321

      check_circle
    • C

      5432

    • D

      01234

    Why

    The while prints i then decrements, while i > 0: prints 5, 4, 3, 2, 1. After i becomes 0, condition is false. Output is "54321".

  3. Sample 3difficulty 2/5

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

    What is printed?

    • A

      15

      check_circle
    • B

      10

    • C

      14

    • D

      21

    Why

    The loop adds 1+2+3+4+5 = 15 to sum.

  4. Sample 4difficulty 2/5

    public static void printReverse(int[] a) {
        for (int i = /* missing */; i >= 0; i--) {
            System.out.println(a[i]);
        }
    }

    Which expression replaces /* missing */?

    • A

      a.length - 1

      check_circle
    • B

      a.length + 1

    • C

      a.length

    • D

      0

    Why

    The last valid index is a.length - 1. Iterate downward from there to 0.

  5. Sample 5difficulty 2/5

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

    What is printed?

    • A

      30

      check_circle
    • B

      25

    • C

      20

    • D

      55

    Why

    i takes values 0, 2, 4, 6, 8, 10. Sum = 0+2+4+6+8+10 = 30.