Home

Tutoring

Subjects

Live Classes

Study Coach

Essay Review

On-Demand Courses

Colleges

Games

Opening subject page...

Loading your content

← Back to quizzes

AP Computer Science a

AP Computer Science a Quiz: While Loops

Practice While Loops in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on While Loops, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

Question 1

Analyze the following code.

// Conditional loop: stop when target is found
int[] data = {2, 4, 6, 8, 10}; // sequence
int i = 0;                     // initialization
int target = 8;
while (i < data.length && data[i] != target) { // condition
    i++;                                           // update
}
System.out.println(i);

What will be the output of the given code?

  1. 2
  2. 3
  3. 4
  4. 5
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop searches through an array for a target value (8), using a compound condition to ensure both array bounds are respected and the target hasn't been found. Choice B is correct because the loop increments i for values at indices 0 (2), 1 (4), and 2 (6), then stops when it finds 8 at index 3, printing i = 3. Choice C is incorrect because it assumes the loop continues past finding the target, misunderstanding how the != condition works. To help students: Practice tracing loops with compound conditions, evaluating each part separately. Use debugging techniques to understand short-circuit evaluation in && conditions.

Question 2

Analyze the following code. How many times will the loop execute?

// Scenario: counting loop prints values from 1 up to 10
int count = 1;               // initialize
while (count < 10) {         // condition
    System.out.println(count);
    count++;                 // update
}
  1. 8 times
  2. 9 times
  3. 10 times
  4. It executes infinitely.
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop starts with count=1 and continues while count < 10, printing count and incrementing it each iteration. Choice B is correct because the loop executes exactly 9 times: when count equals 1, 2, 3, 4, 5, 6, 7, 8, and 9, stopping when count becomes 10 since 10 is not less than 10. Choice C is incorrect because it miscounts by assuming the loop includes count=10, but the condition count < 10 excludes this value. To help students: Create tables showing loop variable values before and after each iteration. Emphasize the difference between < and <= conditions and their impact on iteration count.

Question 3

Analyze the following code.

// Counting loop with a strict bound
int counter = 1;            // initialization
while (counter < 10) {      // condition
    System.out.println(counter);
    counter++;              // update
}

How many times will the loop execute?

  1. 8 times
  2. 9 times
  3. 10 times
  4. It executes indefinitely
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop initializes counter to 1 and iterates while counter < 10, printing values and incrementing counter until the condition becomes false. Choice B is correct because the loop executes for counter values 1, 2, 3, 4, 5, 6, 7, 8, and 9 (exactly 9 times), stopping when counter reaches 10 since 10 < 10 is false. Choice C is incorrect because it reflects confusion between < and <= operators, which is a common off-by-one error. To help students: Create iteration tables showing the counter value before and after each loop execution. Emphasize the importance of testing boundary conditions and understanding when loops terminate.

Question 4

Analyze the following code.

// Conditional loop: search for a value and report if found
int[] values = {3, 6, 9};     // sequence
int i = 0;                    // initialization
int target = 5;
while (i < values.length && values[i] != target) { // condition
    i++;                                           // update
}
System.out.println(i == values.length);

What will be the output of the given code?

  1. true
  2. false
  3. 5
  4. It executes indefinitely
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop searches for a target value (5) in an array, and after the loop, checks if the search was unsuccessful by comparing i to the array length. Choice A is correct because the loop searches through all three elements (3, 6, 9) without finding 5, so i becomes 3 (equal to values.length), making the expression i == values.length evaluate to true. Choice B is incorrect because it assumes the target was found, misunderstanding that when a linear search fails, the index equals the array length. To help students: Practice post-loop analysis to understand what loop variable values indicate about search success or failure. Emphasize the pattern of using index == array.length to detect unsuccessful searches.

Question 5

Analyze the following code.

// Error-checking loop: keep advancing until a valid score is found
int[] attempts = {-3, 12, 7}; // simulated user entries
int index = 0;                // initialization
int score = attempts[index];  // current entry
while (score < 0 || score > 10) { // validate range 0..10
    index++;                      // update
    score = attempts[index];      // next entry in sequence
}
System.out.println(score);

What will be the output of the given code?

  1. 12
  2. -3
  3. 7
  4. It executes indefinitely
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop validates input values, continuing while the score is outside the valid range of 0 to 10, simulating an error-checking mechanism. Choice C is correct because the loop skips -3 (invalid), skips 12 (invalid), then finds 7 (valid) and exits, printing 7. Choice A is incorrect because it assumes the loop stops at the first out-of-range value rather than continuing to search for a valid one. To help students: Practice with validation loops and compound OR conditions. Trace through each iteration showing why values are rejected or accepted based on the range criteria.

Question 6

Analyze the following code.

// Scenario: counting loop with an incorrect update
int count = 1; // initialization
while (count <= 10) { // condition
    System.out.println(count);
    count--; // update (intended to increment)
}

Identify the error in the loop logic.

  1. The update decrements, preventing termination
  2. The condition should be count >= 10
  3. System.out.println must be outside the loop
  4. The code has a Java syntax error
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop intends to count from 1 to 10 but contains a logic error where count is decremented (count--) instead of incremented. Choice A is correct because the decrement operation causes count to become 0, -1, -2, etc., always satisfying count <= 10, creating an infinite loop that never terminates. Choice B is incorrect because changing the condition wouldn't fix the fundamental issue of decrementing when incrementing is needed. To help students: Always verify that loop updates move toward the termination condition. Practice identifying infinite loops by checking if the update brings the variable closer to making the condition false.

Question 7

Analyze the following code.

// Scenario: process an array until a target is found
int[] a = {1, 3, 5, 7, 9};
int index = 0; // initialization
while (index < a.length && a[index] != 7) { // condition
    System.out.println(a[index]); // iterate through sequence
    index++; // update
}

What will be the output of the given code?

  1. Prints 1, 3, 5 each on a new line
  2. Prints 1, 3, 5, 7 each on a new line
  3. Prints 9, 7, 5 each on a new line
  4. No output because the loop never executes
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop prints array elements until finding the target value 7, using a compound condition that ensures both array bounds safety and target checking. Choice A is correct because the loop prints a[0] = 1, a[1] = 3, and a[2] = 5, then stops when index = 3 because a[3] = 7, making the condition false before printing 7. Choice B is incorrect because it assumes 7 gets printed, not recognizing that the loop terminates before printing when the target is found. To help students: Trace execution carefully noting when printing occurs relative to condition checking. Emphasize that the loop body doesn't execute when the condition is false.

Question 8

Analyze the following code. How many times will the loop execute?

// Scenario: processing an array until a target is found
int[] values = {3, 6, 9, 12, 15};
int i = 0;                      // initialize index
while (i < values.length && values[i] != 12) { // stop when 12 is found
    i++;                        // update index to iterate
}
  1. 3 times
  2. 4 times
  3. 5 times
  4. It executes infinitely.
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop searches through an array {3, 6, 9, 12, 15} starting at index 0, continuing while i < values.length AND values[i] != 12. Choice A is correct because the loop executes exactly 3 times: when i=0 (values[0]=3), i=1 (values[1]=6), and i=2 (values[2]=9), then stops when i=3 because values[3]=12. Choice C is incorrect because it counts all array elements, not recognizing that the loop terminates early when finding 12. To help students: Create trace tables showing i, values[i], and condition evaluation at each step. Emphasize how compound conditions with && require both parts to be true for continuation.

Question 9

Analyze the following code. What will be the output of the given code?

// Scenario: counting from 1 to 10 using a while loop
int counter = 1;                // initialize
while (counter <= 10) {         // loop condition controls termination
    System.out.println(counter); // print current value
    counter++;                  // update to progress through the sequence
}
  1. It prints 1 through 9, each on a new line.
  2. It prints 0 through 10, each on a new line.
  3. It prints 1 through 10, each on a new line.
  4. It prints 10 through 1, each on a new line.
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop initializes counter to 1 and iterates while counter <= 10, printing the current value and incrementing counter each time. Choice C is correct because the loop executes exactly 10 times: when counter is 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10, printing each value on a new line before incrementing. Choice A is incorrect because it suggests the loop stops at 9, missing that the condition allows counter to equal 10. To help students: Encourage tracing loop iterations step-by-step with a table showing counter values and outputs. Practice identifying loop boundaries and understanding <= versus < conditions.

Question 10

Analyze the following code.

// Scenario: input-driven loop totals values until sentinel -1
int[] stream = {2, 4, 6, -1};
int i = 0; // initialization
int total = 0;
while (stream[i] != -1) { // stop at sentinel
    total += stream[i]; // process sequence
    i++; // update
}
System.out.println(total);

Which variable is affected by the loop iteration?

  1. Only stream is modified
  2. Only total is modified
  3. Both i and total are modified
  4. Only i is modified
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop accumulates values from the stream array until encountering the sentinel value -1, modifying both the accumulator total and the index i. Choice C is correct because within the loop body, total is modified by the += operation and i is modified by the ++ operation, making both variables change during iteration. Choice B is incorrect because it overlooks that i must be incremented to progress through the array. To help students: Identify all variables that change within the loop body. Practice distinguishing between loop control variables and computation variables.

Question 11

Analyze the following code.

// Scenario: search an array until a target is found
int[] data = {2, 4, 6, 8, 10};
int index = 0; // initialization
while (index < data.length && data[index] != 8) { // stop when found
    index++; // update
}
System.out.println(index);

What will be the output of the given code?

  1. Prints 8
  2. Prints 3
  3. Prints 4
  4. Prints 5
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop searches through the array for the value 8, using a compound condition that checks both array bounds and whether the target has been found. Choice B is correct because the loop increments index from 0 to 3, where data[3] equals 8, causing the condition to become false and the loop to terminate with index = 3. Choice C is incorrect because it reflects counting the number of iterations rather than the final index value. To help students: Practice linear search algorithms and trace the index value at each iteration. Emphasize understanding when compound conditions with && become false - when either part is false.

Question 12

Analyze the following code.

// Counting loop with an incorrect update
int counter = 1;                // initialization
while (counter <= 10) {         // condition
    System.out.println(counter);
    counter--;                  // update
}

Identify the error in the loop logic.

  1. counter should be initialized to 0
  2. The update should increment, not decrement
  3. The condition should be counter >= 10
  4. System.out.println causes a syntax error here
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop has a logical error where counter is decremented (counter--) instead of incremented, creating an infinite loop since counter starts at 1 and keeps getting smaller while remaining <= 10. Choice B is correct because the update should increment to eventually make the condition false, not decrement which moves counter further from the termination condition. Choice A is incorrect because initializing to 0 wouldn't fix the fundamental problem of decrementing instead of incrementing. To help students: Emphasize the importance of ensuring loop variables move toward termination conditions. Practice identifying infinite loops by tracing a few iterations and checking if progress is made toward loop exit.

Question 13

Analyze the following code.

// Input-driven sentinel loop over a predefined sequence
int[] inputs = {1, 2, 3, -1}; // simulated user inputs
int i = 0;                    // initialization
while (i < inputs.length && inputs[i] != -1) { // condition
    System.out.println(inputs[i]);
    i++;                                        // update
}

How many times will the loop execute?

  1. 2 times
  2. 3 times
  3. 4 times
  4. It executes indefinitely
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop processes array elements with a compound condition that checks both array bounds and a sentinel value (-1), ensuring safe array access while looking for a termination signal. Choice B is correct because the loop executes for i = 0 (prints 1), i = 1 (prints 2), and i = 2 (prints 3), then stops when it encounters -1 at index 3, executing exactly 3 times. Choice C is incorrect because it counts the sentinel value iteration, not recognizing that the loop terminates before processing -1. To help students: Practice with compound conditions and understand short-circuit evaluation. Create trace tables showing both parts of the condition and when each causes loop termination.

Question 14

Analyze the following code.

// Counting loop that accumulates a running total
int counter = 1;               // initialization
int sum = 0;
while (counter <= 4) {         // condition
    sum += counter;            // update sum each iteration
    counter++;                 // update counter
}
System.out.println(sum);

Which variable is affected by the loop iteration?

  1. Only counter changes each iteration
  2. Only sum changes each iteration
  3. Both counter and sum change each iteration
  4. Neither variable changes each iteration
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop maintains two variables: counter for loop control and sum for accumulation, demonstrating a common pattern where multiple variables are updated within a single loop. Choice C is correct because both counter (incremented from 1 to 5) and sum (accumulating 1+2+3+4 = 10) change during each iteration of the loop. Choice A is incorrect because it overlooks that sum is also modified with the += operation in each iteration. To help students: Use trace tables with columns for all variables to visualize how each changes. Practice identifying accumulator patterns and distinguishing between loop control variables and computation variables.

Question 15

Analyze the following code.

// Counting from 1 to 10 using a while loop
int counter = 1;                 // initialization
while (counter <= 10) {          // condition controls repetition
    System.out.println(counter); // iterate through the sequence 1..10
    counter++;                   // update
}

What will be the output of the given code?

  1. Prints 1 through 9, each on a new line
  2. Prints 1 through 10, each on a new line
  3. Prints 0 through 10, each on a new line
  4. Prints 10 through 1, each on a new line
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop initializes counter to 1 and iterates while counter <= 10, printing each value and incrementing counter until the condition becomes false. Choice B is correct because the loop executes for counter values 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10, printing each on a new line before counter becomes 11 and the loop terminates. Choice A is incorrect because it assumes the loop stops before reaching 10, which would happen with a condition like counter < 10. To help students: Encourage tracing loop iterations step-by-step, creating a table showing counter values and outputs. Practice identifying loop boundaries and understanding the difference between < and <= conditions.

Question 16

Analyze the following code.

// Scenario: counting from 1 to 10 using a while loop
int count = 1; // initialization
while (count <= 10) { // condition controls termination
    System.out.println(count); // iterate through the sequence
    count++; // update
}

What will be the output of the given code?

  1. Prints 0 through 10, each on a new line
  2. Prints 1 through 10, each on a new line
  3. Prints 1 through 9, each on a new line
  4. Prints 10 through 1, each on a new line
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop initializes count to 1 and iterates, printing count and incrementing it until count > 10, at which point the condition becomes false. Choice B is correct because the loop executes with count values from 1 to 10 inclusive, printing each value on a new line before incrementing. Choice A is incorrect because it assumes the loop starts at 0, which reflects not carefully reading the initialization. To help students: Encourage tracing loop iterations step-by-step, creating a table showing count values and outputs at each iteration. Practice identifying the initial value, condition, and update to predict loop behavior accurately.

Question 17

Analyze the following code.

// Scenario: validate input until it is within 1..5
int[] attempts = {0, 7, 3};
int i = 0; // initialization
int rating = attempts[i];
while (rating < 1 || rating > 5) { // error-checking condition
    i++; // update index
    rating = attempts[i]; // update value
}
System.out.println(rating);

What will be the output of the given code?

  1. Prints 7
  2. Prints 0
  3. Prints 3
  4. Prints 1
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop validates input by continuing while the rating is outside the valid range [1, 5], updating to the next attempt until a valid rating is found. Choice C is correct because the loop processes attempts[0] = 0 (invalid), attempts[1] = 7 (invalid), then attempts[2] = 3 (valid), causing the condition to become false and printing 3. Choice A is incorrect because it confuses the invalid value 7 with the final output. To help students: Practice validation loops with compound OR conditions. Trace through each iteration showing why values are invalid until finding the first valid one.

Question 18

Analyze the following code.

// Scenario: counting odd indices in an array with a while loop
int[] nums = {4, 7, 1, 9, 2};
int index = 1; // initialization
while (index < nums.length) { // condition
    System.out.println(nums[index]); // iterate through the sequence
    index += 2; // update
}

How many times will the loop execute?

  1. 2 times
  2. 3 times
  3. 5 times
  4. 0 times
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop starts with index = 1 and increments by 2 each iteration (index += 2), accessing odd indices of the array until index >= nums.length. Choice A is correct because the loop executes exactly 2 times: first when index = 1 (printing 7), then when index = 3 (printing 9), and terminates when index becomes 5 which equals nums.length. Choice C is incorrect because it reflects confusion about how many elements are accessed versus how many times the loop executes. To help students: Encourage manually tracing the index values (1, 3, 5) and checking the condition at each step. Practice distinguishing between loop iterations and array accesses, especially with non-standard increments.

Question 19

Analyze the following code.

// Scenario: find the first value greater than 10
int[] values = {5, 9, 10, 12, 3};
int index = 0; // initialization
while (index < values.length && values[index] <= 10) { // condition
    index++; // update
}
System.out.println(values[index]);

What will be the output of the given code?

  1. Prints 10
  2. Prints 12
  3. Prints 3
  4. Prints 9
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop searches for the first value greater than 10, using a compound condition to ensure array bounds are respected while checking values. Choice B is correct because the loop increments index past values 5, 9, and 10 (all <= 10), stopping at index = 3 where values[3] = 12, which is greater than 10. Choice A is incorrect because it reflects stopping at 10, misunderstanding the <= condition. To help students: Practice compound conditions with short-circuit evaluation. Trace through showing why 10 doesn't satisfy > 10 and the loop continues.

Question 20

Analyze the following code. What will be the output of the given code?

// Scenario: input-driven loop sums values until sentinel -1
int[] inputs = {2, 4, -1, 10};
int idx = 0;          // initialize
int total = 0;
while (idx < inputs.length && inputs[idx] != -1) {
    total += inputs[idx];  // accumulate
    idx++;                 // update
}
System.out.println(total);
  1. 6
  2. 16
  3. -1
  4. It prints 2 then 4 on separate lines.
Explanation: This question tests AP Computer Science A skills, specifically understanding and predicting the behavior of while loops in Java. A while loop repeatedly executes a block of code as long as its condition evaluates to true, allowing for iteration through a sequence until a specific state is reached. In this code snippet, the while loop processes array {2, 4, -1, 10} accumulating values into total until encountering the sentinel value -1. Choice A is correct because the loop adds inputs[0]=2 and inputs[1]=4 to total (making 6), then stops when inputs[2]=-1, never processing the 10. Choice B is incorrect because it assumes all values including those after the sentinel are summed, misunderstanding that -1 terminates the loop. To help students: Use sentinel-controlled loops to demonstrate input processing patterns. Create trace tables showing how accumulators change and when loops terminate based on special values.