AP Computer Science A · Topic 4.1

while Loops Practice

Part of Iteration.

Practice questions

30

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

  1. Sample 1difficulty 2/5

    int i = 10;
    while (i < 5) {
      System.out.println(i);
      i++;
    }
    System.out.println("done");

    What is printed?

    • A

      done

      check_circle
    • B

      10 done

    • C

      nothing

    • D

      10 11 12 done

    Why

    The while condition (10 < 5) is false at the start, so the loop body never executes. Only "done" prints.

  2. Sample 2difficulty 2/5

    What is printed?

    <code>int i = 0; while (i < 3) { System.out.print(i + " "); i++; } </code></pre>

    • A

      1 2 3

    • B

      Infinite loop

    • C

      0 1 2 3

    • D

      0 1 2

      check_circle

    Why

    Loops while i < 3: prints 0, 1, 2.

  3. Sample 3difficulty 2/5

    int n = 1;
    while (n < 16) {
      n *= 2;
    }
    System.out.println(n);

    What is printed?

    • A

      16

      check_circle
    • B

      8

    • C

      32

    • D

      15

    Why

    n doubles each time: 1, 2, 4, 8, 16. When n becomes 16 the condition n < 16 is false and the loop exits. n is 16.

  4. Sample 4difficulty 3/5

    do {
        System.out.println(i);
        i++;
    } while (i < 0);

    Which loop is equivalent in behavior when i starts at 5?

    • A

      An infinite loop

    • B

      No iterations occur

    • C

      System.out.println(5); i = 6; (loop runs exactly once)

      check_circle
    • D

      Loop runs five times

    Why

    A do-while runs at least once and only repeats while the condition is true. Starting at 5 the body runs once, prints 5, increments to 6, and 6 < 0 is false.

  5. Sample 5difficulty 3/5

    int product = 1;
    for (int i = 1; i <= 5; i++) {
      if (i == 3) continue;
      product *= i;
    }
    System.out.println(product);

    What is printed?

    • A

      40

      check_circle
    • B

      120

    • C

      60

    • D

      24

    Why

    Skip i=3. Product = 1<em>1</em>2<em>4</em>5 = 40.

AP Computer Science A · 4.1 while Loops — Practice Questions | Acemy