AP Computer Science A • Unit 2.7

while Loops

Detailed answer explanations for the Unit 2.7 multiple-choice practice questions.

Q1A
Q2C
Q3B
Q4B
Q5B
Q6B
Q7B
Q8C
Q9A
Q10D
Q11A
Q12C
How to use this page: First try each question without looking at the explanation. Then compare your answer with the key and read why the other choices are not correct.

Answer Explanations

Q1

Consider the following code segment. What is printed as a result of executing the code segment?

int spots = 4;
int notes = 2;
while (spots < 4) {
    notes++;
    spots++;
}
System.out.println(notes + spots);
A6
B7
CNothing is printed.
DThe loop is infinite.
Correct answer: A. The condition is false at the first test, so the body is skipped and the sum 6 is printed.
Explanation

A while condition is checked before every iteration, including the first. Because spots already equals 4, the test fails immediately and neither variable changes. The statement after the loop still runs and prints the original values added together.

  • B is not correct: this value would require the body to run once and increase notes, but the condition fails before any iteration begins.
  • C is not correct: the print statement sits after the loop rather than inside it, so skipping the body does not prevent output.
  • D is not correct: the loop cannot be infinite because its condition is already false, and a body that never runs cannot repeat forever.
Q2

Consider the following code segment. What is printed as a result of executing the code segment?

int i = 10;
int count = 0;
while (i > 4) {
    count++;
    i -= 2;
}
System.out.println(count);
A2
B4
C3
D5
Correct answer: C. The body runs three times, lowering i from 10 to 4, so count ends at 3.
Explanation

Tracing records each condition check and each update. The values of i tested are 10, 8, 6, and 4. The first three tests succeed and increase count; the fourth fails because 4 is not greater than 4.

  • A is not correct: after two passes i is 6, which is still greater than 4, so the loop runs at least once more.
  • B is not correct: a fourth pass would need i to stay greater than 4, but the test fails once i reaches 4.
  • D is not correct: the loop subtracts 2 each pass and stops well before i reaches 0, so this many iterations never occur.
Q3

Consider the following code segment. What is printed as a result of executing the code segment?

int total = 0;
int step = 1;
while (step <= 4) {
    total += step;
    if (total > 4) {
        total--;
    }
    step++;
}
System.out.println(total);
A6
B8
C9
DThe loop is infinite.
Correct answer: B. Each pass adds step to total, and the inner if subtracts one on the last two passes, leaving 8.
Explanation

A loop body can contain an if statement, so some iterations update a variable and others do not. The running total reaches 1, 3, 6, and 9 right after each addition, and the inner test fires only for the last two.

  • A is not correct: this is the running total partway through, before the inner if has subtracted anything, so two decreases are missing.
  • C is not correct: this is the value reached on the final pass before the inner if subtracts one, so the last decrease is missing.
  • D is not correct: step increases on every pass, so the condition eventually becomes false and the loop makes progress toward stopping.
Q4

Consider the following code segment. The user enters red, blue, and bye, in that order. What is printed?

String message = input.nextLine();
int count = 0;

while (!message.equals("bye")) {
    count++;
    message = input.nextLine();
}

System.out.println(count);
A1
B2
C3
DThe loop is infinite.
Correct answer: B. The two non-sentinel messages are counted, and "bye" stops the loop before the body can count it.
Explanation

In a sentinel-controlled loop the first value is read before the loop so the condition has something to test, and a new value is read at the end of the body. Because the condition is checked before the body, the sentinel is never processed or counted.

  • A is not correct: both red and blue satisfy the condition, so the body runs twice rather than only once.
  • C is not correct: the sentinel is tested before the body runs, so "bye" ends the loop without adding to count.
  • D is not correct: each pass reads a new value, so the loop eventually reaches the sentinel and its condition becomes false.
Q5

Consider the following code segment. What is printed as a result of executing the code segment?

int left = 2;
int right = 11;
while (left < right) {
    left += 3;
    right -= 2;
}
System.out.println(left);
System.out.println(right);
A5, then 9
B8, then 7
C11, then 4
DThe loop is infinite.
Correct answer: B. Two passes move left from 2 to 8 and right from 11 to 7, then the test fails.
Explanation

Both variables change on every iteration, so a trace table tracks each one. After the first pass left is 5 and right is 9; after the second pass the condition is false, so the body does not run again.

  • A is not correct: these are the values after only one pass, but 5 is still less than 9, so the body runs again.
  • C is not correct: a third pass never happens, because the condition is tested before each body and it already fails after the second pass.
  • D is not correct: the two variables move toward each other on every pass, so the condition reaches false and the loop stops.
Q6

Consider the following code segment. What is printed as a result of executing the code segment?

int i = 1;
while (i <= 5) {
    System.out.print(i + " ");
    i += 2;
}
A1 2 3 4 5
B1 3 5
C2 4
D1 3 5 7
Correct answer: B. The counter starts at 1 and grows by 2, so the loop prints 1 3 5 before the test fails.
Explanation

The three control steps are visible here: i is initialized before the loop, tested in the header, and updated inside the body. Because the update adds 2, only every other value is printed, and the loop stops once the counter passes 5.

  • A is not correct: an update of 2 skips values, so consecutive numbers are never printed; that output would need an increase of 1.
  • C is not correct: the counter is initialized to 1 and printed before it is updated, so the first printed value is 1.
  • D is not correct: 7 is greater than 5, so the condition fails at that point and the value is never printed.
Q7

Consider the following code segment. Which change to the update would make the loop terminate?

int tickets = 12;
while (tickets > 0) {
    System.out.println(tickets);
    tickets += 2;
}
AReplace it with tickets += 1;.
BReplace it with tickets -= 3;.
CReplace it with tickets *= 2;.
DRemove the update.
Correct answer: B. Subtracting 3 each pass moves tickets toward the stopping condition, so the loop eventually ends.
Explanation

A loop should make progress toward a stopping condition. The condition here ends the loop only when tickets is no longer greater than 0, so the update has to lower the value rather than raise it.

  • A is not correct: adding 1 still raises tickets, so the condition never becomes false and the loop remains infinite.
  • C is not correct: doubling tickets raises the value even faster, which moves it away from the stopping condition instead of toward it.
  • D is not correct: without an update tickets would keep its starting value, the condition would stay true, and the loop would never stop.
Q8

Which condition continues loading while packages remain and space is available?

Apacks > 0 || load < cap
Bpacks == 0 && load < cap
Cpacks > 0 && load < cap
Dpacks > 0 && load >= cap
Correct answer: C. Both requirements have to hold at the same time, so the two tests are joined with &&.
Explanation

A while condition can be any Boolean expression, including a compound expression that uses && or ||. Loading continues only while packages remain and space is still available, so both parts must be true for the body to run.

  • A is not correct: || keeps the loop running when only one part holds, so loading would continue even after space ran out.
  • B is not correct: packs == 0 is true only when no packages remain, which is the opposite of the intended requirement.
  • D is not correct: load >= cap is true when space has run out, so this condition keeps loading exactly when it should stop.
Q9

When is the condition of a while loop checked?

ABefore each iteration begins
BOnly after the loop body runs once
COnly when the loop ends
DOnly when the body contains an if
Correct answer: A. The condition is tested before every iteration, including the first, so the body never runs before a test.
Explanation

A while loop repeatedly executes its body while a Boolean condition is true. After each pass through the body, Java returns to the condition and tests it again, which is why the body can execute zero times.

  • B is not correct: the first test happens before any pass, which is how a loop with an initially false condition runs zero times.
  • C is not correct: the condition is checked repeatedly while the loop runs, not only at the moment the loop finishes.
  • D is not correct: an if inside the body only changes what some iterations do; it does not affect when the condition is tested.
Q10

Which statement reads the next word in a sentinel loop?

Aword = "bye";
Bword.length();
CSystem.out.println(word);
Dword = input.nextLine();
Correct answer: D. Reading the next value means calling input.nextLine() and storing the result back in word.
Explanation

A sentinel-controlled loop reads the first value before the loop and reads a new value at the end of the body. Without that second read, the condition would test the same value on every check and the loop would not progress.

  • A is not correct: assigning the sentinel directly ends the loop instead of supplying the next value entered by the user.
  • B is not correct: word.length() reports information about the current value; it does not replace that value with a new one.
  • C is not correct: printing displays the current value, so the condition would keep testing the same value and the loop would not progress.
Q11

Which condition includes lockers 1 through 12?

AChange the condition to locker <= 12.
BChange the condition to locker > 12.
CStart with locker = 0.
DIncrement locker twice.
Correct answer: A. The condition locker <= 12 is still true at the final locker, so every locker in the range is processed.
Explanation

An off-by-one error occurs when a loop runs one time too many or one time too few, often because the condition uses the wrong relational operator. Including the last value requires an operator that still succeeds at that value.

  • B is not correct: this condition is false at the first test, so the body would be skipped and no locker would be processed.
  • C is not correct: starting earlier shifts which value comes first rather than fixing the boundary, and it adds a locker below 1.
  • D is not correct: incrementing twice each pass skips values instead of extending the range, so the loop still misses the final locker.
Q12

Which information belongs in a two-variable trace table?

AOnly the final output
BOnly the declarations
CThe condition result and updated values
DAll possible variable values
Correct answer: C. A trace table records each condition check together with the values the body produces for both variables.
Explanation

Tracing verifies that a loop behaves as intended, one iteration at a time. When two variables change on every iteration, the table tracks both, showing the result of each condition check and the value of each variable after the body.

  • A is not correct: the final output is what a trace confirms, so a table that records only that result hides the steps leading to it.
  • B is not correct: declarations supply only the starting values, and a trace has to record what changes on each pass through the body.
  • D is not correct: a trace records the values that actually occur at each check, not every value the variables could possibly hold.