AP Computer Science a Quiz: Implementing Selection And Iteration Algorithms
19 questions · exam conditions
0:00
Implementing Selection And Iteration AlgorithmsQuestion 1 of 19

Given the task requirements, what will be the output after executing the provided code snippet?

You are implementing selection sort. After each outer-loop pass, the smallest remaining element is swapped into position i. Use iteration for scanning and selection for tracking the minimum.

Input: nn, then nn integers. Output: sorted array. Constraints: 1n1001 \le n \le 100; values in [-1000,1000]. Example input: 4 5 2 9 1 Example output: 1 2 5 9

Code snippet:

int[] a = {5, 2, 9, 1};

**for** (int i = 0; i < a.length - 1; i++) {
    int min = i;
    **for** (int j = i + 1; j < a.length; j++) {
        **if** (a[j] < a[min]) {
            min = j;
        }
    }
    int tmp = a[i];
    a[i] = a[min];
    a[min] = tmp;
}
System.out.print(a[0] + " " + a[1]);
1 2
2 1
5 2
1 5
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Implementing Selection And Iteration Algorithms

Practice Implementing Selection And Iteration Algorithms 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 Implementing Selection And Iteration Algorithms, 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.

All questions

Question 1

Given the task requirements, what will be the output after executing the provided code snippet?

You are implementing selection sort. After each outer-loop pass, the smallest remaining element is swapped into position i. Use iteration for scanning and selection for tracking the minimum.

Input: nn, then nn integers. Output: sorted array. Constraints: 1n1001 \le n \le 100; values in [-1000,1000]. Example input: 4 5 2 9 1 Example output: 1 2 5 9

Code snippet:

int[] a = {5, 2, 9, 1};

**for** (int i = 0; i < a.length - 1; i++) {
    int min = i;
    **for** (int j = i + 1; j < a.length; j++) {
        **if** (a[j] < a[min]) {
            min = j;
        }
    }
    int tmp = a[i];
    a[i] = a[min];
    a[min] = tmp;
}
System.out.print(a[0] + " " + a[1]);
  1. 1 2 (correct answer)
  2. 2 1
  3. 5 2
  4. 1 5

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on selection sort implementation and understanding its state after partial execution. Selection sort works by finding the minimum element in the unsorted portion and swapping it into the next sorted position, building the sorted array from left to right. In this scenario, the array {5, 2, 9, 1} undergoes selection sort, and we need to determine the first two elements after the algorithm completes. Choice A (1 2) is correct because in the first pass (i=0), the algorithm finds the minimum 1 at index 3 and swaps it with 5, giving {1, 2, 9, 5}; in the second pass (i=1), it finds minimum 2 already at index 1 so no swap occurs; after all passes, the sorted array is {1, 2, 5, 9}, so a[0]=1 and a[1]=2. Choice D (1 5) might tempt students who think only one pass occurs, but the loop continues for all necessary passes. To help students: Trace selection sort step-by-step, showing the array state after each outer loop iteration. Emphasize that selection sort makes n-1 passes for an n-element array, progressively building the sorted portion from the left.

Question 2

You are writing a menu-driven calculator for students to practice loops. The program repeatedly reads a command character: 'A' adds a value to a running total, 'S' subtracts a value, and 'Q' quits. For 'A' and 'S', the next input is an integer value. The program must use iteration with a do-while loop to run at least once, and selection (if/else if/else) to handle commands. Input: a sequence of commands and values ending with 'Q'. Output: after quitting, print "total: X". Constraints: values are in [100,100][-100, 100]; at most 20 commands before 'Q'.

Given the task requirements, which of the following correctly implements the required do-while loop condition?

char cmd;
int total = 0;
do {
    cmd = in.next().charAt(0);
    // handle A/S/Q
} while (/* condition */);
System.out.println("total: " + total);
  1. cmd == 'Q'
  2. cmd != 'Q' (correct answer)
  3. cmd = 'Q'
  4. cmd.equals('Q')

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on do-while loop conditions for menu-driven programs within Java coding tasks. A do-while loop executes its body at least once and continues while the condition is true, so for a quit command 'Q', the loop should continue while the command is NOT 'Q'. In this scenario, the program needs to keep running until the user enters 'Q', which means the loop condition should check that cmd is not equal to 'Q'. Choice B (cmd != 'Q') is correct because it properly implements the loop to continue while the command is anything other than 'Q', allowing the program to process 'A' and 'S' commands and only exit when 'Q' is entered. Choice A (cmd == 'Q') is incorrect because it would cause the loop to continue only when cmd equals 'Q', immediately exiting after any other command. To help students: Emphasize the difference between while and do-while loops, and clarify that do-while conditions determine continuation, not termination. Practice writing menu-driven programs with various exit conditions to build familiarity with the pattern.

Question 3

You are processing student grades. The program reads nn integer scores (0–100). It uses iteration to compute the average and selection to count how many are passing (>= 60). Input: first line nn, second line has nn scores. Output: two lines: "avg: X" (double, one decimal) and "passing: Y". Constraints: 0n250 \le n \le 25. If n=0n=0, output "avg: 0.0" and "passing: 0".

Based on the problem description, what will be the output after executing the provided code snippet for input n=0?

int n = in.nextInt();
int sum = 0;
int passing = 0;
for (int i = 0; i < n; i++) {
    int s = in.nextInt();
    sum += s;
    if (s >= 60) {
        passing++;
    }
}
double avg = (n == 0) ? 0.0 : (double) sum / n;
System.out.printf("avg: %.1f\n", avg);
System.out.println("passing: " + passing);
  1. avg: 0.0\npassing: 0 (correct answer)
  2. avg: NaN\npassing: 0
  3. avg: 0\npassing: 0
  4. Runtime error (division by zero)

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on edge case handling with conditional operators within Java coding tasks. The program must handle the special case where n=0 to avoid division by zero, using the ternary operator to set avg to 0.0 when n equals 0. In this scenario, when n=0, the for loop doesn't execute at all (since i < 0 is immediately false), leaving sum and passing at their initial values of 0, and the conditional expression correctly evaluates to 0.0 for the average. Choice A is correct because the code properly handles the n=0 case: the ternary operator returns 0.0, printf formats it as '0.0' with one decimal place, and passing remains 0, producing the exact output specified. Choice D is incorrect because the code explicitly prevents division by zero using the conditional operator. To help students: Emphasize the importance of edge case testing, especially with empty inputs, and demonstrate how conditional operators can elegantly handle special cases. Practice tracing code with boundary values like 0, 1, and maximum values.

Question 4

You are implementing binary search for a library kiosk. The program reads a sorted array of nn integers (book codes) and a target code. It must use iteration (while) and selection to narrow the search: compare target to middle element and adjust low/high accordingly. Input: first line nn, second line nn sorted integers, third line target. Output: index if found, else -1. Constraints: 1n1001 \le n \le 100; codes are 0–9999.

Given the task requirements, which of the following correctly implements the required loop update when target is less than mid value?

int low = 0, high = arr.length - 1;
while (low <= high) {
    int mid = (low + high) / 2;
    if (target == arr[mid]) return mid;
    else if (target < arr[mid]) {
        // update here
    } else {
        low = mid + 1;
    }
}
return -1;
  1. high = mid - 1; (correct answer)
  2. high = mid + 1;
  3. low = mid - 1;
  4. low = mid;

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on binary search boundary updates within Java coding tasks. Binary search narrows the search space by comparing the target with the middle element and adjusting either the low or high boundary accordingly, eliminating half of the remaining elements each iteration. In this scenario, when the target is less than arr[mid], we know the target must be in the left half of the current range, so we need to update high to exclude the right half including mid itself. Choice A (high = mid - 1) is correct because it properly implements the search space reduction by setting high to one position before mid, excluding all elements from mid onwards since they are all greater than or equal to arr[mid]. Choice B (high = mid + 1) is incorrect as it would expand the search range rightward instead of narrowing it leftward when target is smaller. To help students: Use visual representations of arrays with low, mid, and high pointers to show how the search space shrinks, and emphasize that we can exclude mid itself since we've already checked it. Practice tracing binary search with specific examples to understand boundary movements.

Question 5

Based on the problem description, what will be the output after executing the provided code snippet?

Problem description (Simulated Environment) A Java traffic light simulation cycles through three states: GREEN, YELLOW, RED. Each step prints the current state, then advances to the next state using selection (if/else if/else). The simulation runs for a fixed number of steps using iteration.

Task requirements

  • Start in GREEN.
  • After GREEN go to YELLOW, after YELLOW go to RED, after RED go to GREEN.
  • Print one state per line for steps iterations.

Input

  • One integer steps

Output

  • steps lines of states

Constraints

  • 1steps201 \le steps \le 20

Example Input: 4 Output: GREEN YELLOW RED GREEN

Code snippet:

String state = "GREEN";
int steps = 5;
for (int i = 0; i < steps; i++) {
    System.out.println(state);
    if (state.equals("GREEN")) state = "YELLOW";
    else if (state.equals("YELLOW")) state = "RED";
    else state = "GREEN";
}
  1. GREEN, YELLOW, RED, GREEN, YELLOW (correct answer)
  2. GREEN, RED, YELLOW, GREEN, RED
  3. YELLOW, RED, GREEN, YELLOW, RED
  4. GREEN, YELLOW, RED, YELLOW, GREEN

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on state machine logic using if-else chains within a for loop in Java coding tasks. The traffic light cycles through states GREEN→YELLOW→RED→GREEN in a fixed pattern, with the current state printed before transitioning to the next. In this scenario, starting from GREEN and running 5 iterations: print GREEN then change to YELLOW, print YELLOW then change to RED, print RED then change to GREEN, print GREEN then change to YELLOW, print YELLOW then change to RED. Choice A is correct because it accurately traces the execution where each iteration prints the current state before the if-else chain updates it, producing the sequence GREEN, YELLOW, RED, GREEN, YELLOW. Choice D is incorrect because it suggests the pattern reverses or changes in some way, but the code implements a consistent one-way cycle. To help students: Use state diagrams to visualize transitions and trace execution with a table showing iteration number, printed state, and next state. Encourage students to distinguish between printing current state versus next state in their trace tables.

Question 6

Given the task requirements, which of the following correctly implements the required loop structure?

Implement insertion sort to sort an integer array in ascending order. Use iteration to shift larger elements to the right, and selection to decide when shifting stops.

Input: nn, then nn integers. Output: the sorted array. Constraints: 1n1001 \le n \le 100; values in [-1000, 1000]. Example input: 4 5 2 9 1 Example output: 1 2 5 9

Choose the correct inner loop for insertion sort (assume key = a[i] and j = i - 1):

  1. while (j>=0 && a[j]>key) { a[j+1]=a[j]; j--; } (correct answer)
  2. while (j>0 && a[j]<key) { a[j+1]=a[j]; j--; }
  3. while (j>=0 || a[j]>key) { a[j+1]=a[j]; j--; }
  4. while (j>=0 && a[j]>key) { a[j]=a[j+1]; j--; }

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on the inner loop logic of insertion sort for shifting elements. Insertion sort maintains a sorted portion and inserts each new element by shifting larger elements right until finding the correct position. In this scenario, the task requires implementing the shifting phase where elements larger than the key are moved one position right, starting from position j and moving leftward. Choice A (while (j>=0 && a[j]>key) { a[j+1]=a[j]; j--; }) is correct because it checks j>=0 to avoid array bounds errors, uses && to ensure both conditions are met, checks a[j]>key to shift only larger elements, correctly shifts with a[j+1]=a[j], and decrements j to move left. Choice C is incorrect because || would cause array access errors when j<0, and Choice D incorrectly assigns a[j]=a[j+1] which moves elements left instead of right. To help students: Visualize insertion sort as making space for the key by shifting elements right. Practice tracing the algorithm with small arrays and emphasize the importance of && versus || in compound conditions.

Question 7

Given the task requirements, what will be the output after executing the provided code snippet?

Problem description (Data Processing) A teacher's Java program processes a list of student scores (0–100). It must compute the class average using iteration and assign a letter grade using selection:

  • if score 90\ge 90: A
  • else if score 80\ge 80: B
  • else if score 70\ge 70: C
  • else if score 60\ge 60: D
  • else: F

The program prints each letter grade on its own line, then prints the integer average (using integer division).

Input

  • Line 1: integer n (number of scores)
  • Next n lines: one integer score each

Output

  • n lines of letter grades
  • Final line: Average: X

Constraints

  • 0n300 \le n \le 30
  • Scores are integers in [0,100][0, 100]
  • If n == 0, print only Average: 0

Example Input: 3 90 80 70 Output: A B C Average: 80

Code snippet:

int[] scores = {88, 59, 90};
int sum = 0;
for (int i = 0; i < scores.length; i++) {
    int s = scores[i];
    sum += s;
    if (s >= 90) System.out.println("A");
    else if (s >= 80) System.out.println("B");
    else if (s >= 70) System.out.println("C");
    else if (s >= 60) System.out.println("D");
    else System.out.println("F");
}
System.out.println("Average: " + (sum / scores.length));
  1. B, F, A, then Average: 79 (correct answer)
  2. B, F, A, then Average: 80
  3. B, D, A, then Average: 79
  4. A, F, B, then Average: 79

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on grade assignment using if-else chains and average calculation within Java coding tasks. The program processes an array of scores {88, 59, 90}, assigning letter grades based on threshold conditions and computing the integer average. In this scenario, the loop processes each score: 88 falls in the 80-89 range (B), 59 is below 60 (F), and 90 is exactly 90 (A), while the sum 237 divided by 3 gives 79 using integer division. Choice A is correct because it properly traces the execution: score 88 prints 'B', score 59 prints 'F', score 90 prints 'A', and the average calculation (88+59+90)/3 = 237/3 = 79 in integer division. Choice B is incorrect because integer division of 237/3 yields 79, not 80, as the decimal portion is truncated. To help students: Practice tracing through if-else chains with boundary values, and emphasize the difference between integer and floating-point division. Encourage students to manually calculate averages and verify their understanding of integer truncation.

Question 8

Based on the problem description, which of the following correctly implements the required loop structure?

Implement binary search on a sorted integer array to find the index of target. Use iteration to repeatedly narrow the search range and selection (if/else) to choose whether to search left or right. If not found, output -1.

Input: nn, then nn sorted integers, then target. Output: index of target or -1. Constraints: 1n10001 \le n \le 1000; values in [-100000, 100000]. Example input: 5 1 4 7 9 12 9 Example output: 3

Choose the correct loop condition for binary search (assume low and high are indices):

  1. while (low < high)
  2. while (low <= high) (correct answer)
  3. while (low == high)
  4. while (low >= high)

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on the correct loop condition for binary search implementation. Binary search requires maintaining a valid search range and must handle the case where low and high indices meet at the target element. In this scenario, the task requires implementing binary search which repeatedly narrows the search range by comparing the middle element with the target and adjusting low or high accordingly. Choice B (while (low <= high)) is correct because it continues searching while there's at least one element in the range (when low equals high, there's still one element to check), and properly terminates when low > high indicates an empty range meaning the target wasn't found. Choice A (while (low < high)) is incorrect because it would miss checking the case where low equals high, potentially failing to find elements that happen to be at that single remaining position. To help students: Trace binary search with small arrays, especially edge cases with 1-2 elements. Emphasize that low <= high maintains the invariant that the search range is valid and non-empty.

Question 9

Based on the problem description, which condition will correctly exit the loop under described circumstances?

Problem description (Game Logic) A Java program asks the user to enter a positive menu choice (1–5). It must keep prompting until the user enters a valid choice. The program uses a do-while loop so the prompt runs at least once, and selection to print Invalid when the value is out of range.

Task requirements

  • Prompt once, read choice.
  • If choice is outside 1–5, print Invalid and prompt again.
  • Stop only when choice is valid.

Input

  • A sequence of integers, one per prompt

Output

  • Invalid for each invalid entry
  • No extra output after a valid entry

Constraints

  • Inputs are integers

Example Input: 0 7 3 Output: Invalid Invalid

Loop skeleton:

do {
    // prompt, read choice
    if (choice < 1 || choice > 5) {
        System.out.println("Invalid");
    }
} while (/* condition */);
  1. choice < 1 || choice > 5 (correct answer)
  2. choice >= 1 && choice <= 5
  3. choice < 1 && choice > 5
  4. choice == 1 && choice == 5

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on do-while loop continuation conditions for input validation within Java coding tasks. A do-while loop for input validation should continue (repeat) when the input is invalid, meaning the condition should be true for invalid inputs and false for valid inputs. In this scenario, valid choices are 1-5 inclusive, so invalid choices are those less than 1 OR greater than 5, and the loop should continue while the choice remains invalid. Choice A is correct because choice < 1 || choice > 5 evaluates to true for all invalid values (0, -1, 6, 7, etc.) and false for valid values (1, 2, 3, 4, 5), causing the loop to repeat for invalid input and exit for valid input. Choice B is incorrect because it represents the condition for valid input, which would cause the loop to continue when input is valid and exit when invalid - the opposite of the desired behavior. To help students: Draw number lines showing valid and invalid ranges, and practice negating conditions to switch between 'is valid' and 'is invalid' logic. Encourage students to test boundary values (0, 1, 5, 6) to verify their conditions work correctly.

Question 10

Given the task requirements, what will be the output after executing the provided code snippet?

You are implementing a linear search on an array of integers to find the first index of a target value. If the target is not found, output -1. Use iteration to scan the array and selection to stop when found.

Input: nn, then nn integers, then target. Output: the first index of target, or -1. Constraints: 1n2001 \le n \le 200; integers in [-1000, 1000]. Example input: 5 3 7 7 2 9 7 Example output: 1

Code snippet:

int[] a = {3, 7, 7, 2, 9};
int target = 7;
int idx = -1;

**for** (int i = 0; i < a.length; i++) {
    **if** (a[i] == target) {
        idx = i;
        **break**;
    }
}
System.out.print(idx);
  1. 0
  2. 1 (correct answer)
  3. 2
  4. -1

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on linear search with early termination using break statements. Linear search examines elements sequentially until finding the target or reaching the end, and the break statement provides efficient early exit when the target is found. In this scenario, the task requires finding the first occurrence of target value 7 in the array {3, 7, 7, 2, 9}, which appears at index 1 (0-based indexing). Choice B (1) is correct because the loop starts at i=0, checks a[0]=3 (not equal to 7), then checks a[1]=7 (equals target), sets idx=1, and breaks out of the loop, resulting in output 1. Choice A (0) would be incorrect as that's where 3 is located, and Choice C (2) would be the second occurrence of 7, but break ensures we stop at the first. To help students: Trace through the code step-by-step with actual values, emphasizing how break immediately exits the loop. Practice distinguishing between finding first occurrence versus all occurrences of a target value.

Question 11

Given the task requirements, identify the error in the following if-else implementation.

You are implementing selection sort on an integer array to sort it in ascending order. The algorithm must use iteration to find the smallest remaining value and selection to update the current minimum index.

Input: first an integer nn, then nn integers. Output: the sorted array on one line, space-separated. Constraints: 1n1001 \le n \le 100; each integer is in [-1000, 1000]. Example input: 4 5 2 9 1 Example output: 1 2 5 9

Code snippet inside the inner loop:

**if** (arr[j] < arr[minIndex]) {
    minIndex = j;
} **else if** (arr[j] > arr[minIndex]) {
    minIndex = j; // intended: do nothing
}
  1. Second branch wrongly updates minIndex (correct answer)
  2. Missing semicolon after minIndex = j
  3. Must use while instead of if
  4. Comparison should be arr[j] == arr[minIndex]

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on proper if-else logic within selection sort implementation. Selection sort works by finding the minimum element in the unsorted portion and swapping it with the first unsorted element, requiring careful tracking of the minimum index. In this scenario, the task requires correctly updating minIndex only when a smaller element is found, but the else if branch incorrectly updates minIndex when a larger element is found. Choice A is correct because the second branch (else if) wrongly updates minIndex when arr[j] > arr[minIndex], which would cause the algorithm to track the maximum instead of minimum, breaking the sorting logic. Choice B is incorrect because semicolons are not required after assignment statements in Java, and Choice C is incorrect because if statements are appropriate here - we don't need repeated checking with while. To help students: Emphasize that in selection sort, we only update minIndex when finding a smaller value, never for larger values. Practice tracing through the algorithm step-by-step to understand when and why index updates occur.

Question 12

Based on the problem description, what will be the output after executing the provided code snippet?

You are processing student grades to compute an average. The program reads grades until -1. It should ignore the sentinel and compute the average of entered grades. Use selection to avoid dividing by zero when no grades were entered.

Input: integers ending with -1. Output: "No grades" or average. Constraints: grades in [0,100]; at most 200 grades. Example input: -1 Example output: No grades

Code snippet:

int sum = 0;
int count = 0;
int grade = -1;

**do** {
    grade = scan.nextInt();
    **if** (grade != -1) {
        sum += grade;
        count++;
    }
} **while** (grade != -1);

**if** (count == 0) {
    System.out.print("No grades");
} **else** {
    System.out.print((double) sum / count);
}

If the input is just -1, what is printed?

  1. 0.0
  2. No grades (correct answer)
  3. -1.0
  4. Runtime error

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on do-while loops and conditional output based on input validation. The do-while loop always executes at least once before checking the condition, which is crucial for reading input before testing it. In this scenario, when input is just -1, the do-while loop executes once: it reads -1, the if condition (grade != -1) is false so nothing is added to sum or count, then the while condition (grade != -1) is false so the loop exits with count=0. Choice B ("No grades") is correct because after the loop, count equals 0, so the if (count == 0) condition is true, printing "No grades" as required when no valid grades were entered. Choice A (0.0) would occur if count > 0 but sum = 0, which doesn't happen here since no grades were processed. To help students: Trace do-while loops carefully, noting they always execute once. Emphasize the importance of handling edge cases like empty input and practice identifying when counters remain at initial values.

Question 13

You are implementing insertion sort for a small classroom tool that sorts quiz scores. The program reads nn integers into an array (unsorted), then sorts ascending using insertion sort. It must use iteration with a for loop for the outer pass and a while loop to shift elements. Input: first line nn, second line nn integers. Output: the sorted array on one line separated by spaces. Constraints: 1n501 \le n \le 50; values are in [1000,1000][-1000, 1000].

Given the task requirements, which of the following correctly implements the required inner loop structure?

for (int i = 1; i < arr.length; i++) {
    int key = arr[i];
    int j = i - 1;
    // inner loop here
}
  1. while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; (correct answer)
  2. while (j > 0 && arr[j] > key) { arr[j] = arr[j - 1]; j--; } arr[j] = key;
  3. while (j >= 0 || arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key;
  4. while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j++; } arr[j + 1] = key;

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on insertion sort's inner loop mechanics within Java coding tasks. Insertion sort requires shifting elements rightward to make space for the key element, using a while loop that continues as long as we haven't reached the beginning of the array AND the current element is greater than the key. In this scenario, the task requires correctly implementing the shifting mechanism where elements are moved one position to the right until the correct insertion point is found. Choice A is correct because it properly implements both conditions (j >= 0 && arr[j] > key) with logical AND, shifts elements correctly (arr[j + 1] = arr[j]), decrements j to move left, and places the key at the correct position (arr[j + 1] = key). Choice C is incorrect due to using logical OR (||) instead of AND (&&), which would cause the loop to continue even when j becomes negative, resulting in an array index out of bounds error. To help students: Use visualization tools to show how elements shift during insertion sort, and emphasize the importance of compound conditions in preventing array access errors. Practice tracing the algorithm with small arrays to understand the shifting pattern.

Question 14

You are writing a grade-processing program for a teacher. The program reads nn integer scores (0–100) into an array and then prints each student's letter grade and the class average. Letter grades are assigned using selection: if score >= 90 then 'A', else if >= 80 then 'B', else if >= 70 then 'C', else if >= 60 then 'D', else 'F'. The program must use iteration to (1) read scores, (2) compute the sum, and (3) print results. Input format: first line nn, second line contains nn scores separated by spaces. Output format: one line per student in the form "score: letter", then a final line "avg: X" where X is the average as a double with one decimal. Constraints: 0n300 \le n \le 30; each score is 0–100. Edge cases: if n=0n=0, print only "avg: 0.0".

Based on the task requirements, which condition will correctly exit the input-reading loop?

int i = 0;
// read n scores into scores[]
while (/* condition */) {
    scores[i] = in.nextInt();
    i++;
}
  1. i <= n
  2. i < n (correct answer)
  3. i != n - 1
  4. i > n

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on loop condition design within Java coding tasks. The while loop needs to continue reading scores as long as we haven't read all n scores, which means the condition should allow the loop to run while i is less than n. In this scenario, the task requires correctly setting loop bounds to read exactly n scores into the array, where i starts at 0 and increments after each read. Choice B (i < n) is correct because it properly implements the loop to run n times (from i=0 to i=n-1), ensuring all n scores are read into the array. This demonstrates understanding of zero-based indexing and proper loop termination. Choice A (i <= n) is incorrect due to an off-by-one error, which would attempt to read n+1 scores and cause an array index out of bounds exception. To help students: Emphasize the relationship between array indices (0 to n-1) and loop counters, and practice tracing loops with small values of n. Encourage students to verify loop bounds by checking the first and last iterations.

Question 15

You are implementing linear search for a school inventory app. The program reads a sorted array of nn integers (IDs) and then searches for a target ID using linear search from left to right. It must use iteration and selection: if the current element equals the target, return its index; else continue. Input: first line nn, second line nn integers, third line target. Output: the index if found, otherwise -1. Constraints: 0n1000 \le n \le 100; IDs are 0–9999.

Given the task requirements, which of the following correctly implements the required loop structure?

int index = -1;
for (int i = 0; i < arr.length; i++) {
    // check here
}
System.out.println(index);
  1. if (arr[i] == target) { index = i; }
  2. if (arr[i] == target) { index = i; break; } (correct answer)
  3. if (arr[i] = target) { index = i; break; }
  4. if (arr[i] != target) { index = i; break; }

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on linear search implementation with early termination within Java coding tasks. Linear search requires checking each element sequentially until the target is found, at which point the search should stop immediately to avoid overwriting the found index with later non-matching elements. In this scenario, the task requires finding the first occurrence of the target and returning its index, which necessitates both setting the index and breaking out of the loop. Choice B is correct because it properly implements the search by checking equality (arr[i] == target), storing the index (index = i), and immediately exiting the loop (break) to preserve the first found index. Choice A is incorrect because without the break statement, the loop continues and index would be overwritten if the target appears multiple times, returning the last occurrence instead of the first. To help students: Demonstrate the difference between finding first versus last occurrence, and emphasize the role of break in controlling loop flow. Practice tracing searches with arrays containing duplicate values to understand why early termination matters.

Question 16

You are generating a number pyramid for a student worksheet. The user enters a positive integer nn (1–9). The program prints nn lines. Line ii (1-indexed) contains the number ii repeated ii times, with no spaces (e.g., for n=4n=4 the lines are: 1, 22, 333, 4444). The program must use iteration (nested loops) and may use selection to validate input: if nn is outside 1–9, print "invalid" and stop. Input: one integer nn. Output: either the pyramid or "invalid".

Given the task requirements, which of the following correctly implements the required loop structure?

for (int i = 1; i <= n; i++) {
    // inner loop prints i, i times
    System.out.println();
}
  1. for (int j = 1; j <= i; j++) { System.out.print(i); } (correct answer)
  2. for (int j = 0; j < n; j++) { System.out.print(i); }
  3. for (int j = 1; j < i; j++) { System.out.print(i); }
  4. for (int j = i; j >= 1; j--) { System.out.print(j); }

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on nested loop design for pattern generation within Java coding tasks. The pyramid pattern requires line i to contain the digit i repeated exactly i times, which means the inner loop must run i iterations to print i that many times. In this scenario, the outer loop correctly runs from i=1 to i=n, and the inner loop needs to print the value i exactly i times on each line. Choice A (for (int j = 1; j <= i; j++)) is correct because it properly implements the inner loop to run i times (from j=1 to j=i inclusive), printing i on each iteration to create the required pattern. Choice C (for (int j = 1; j < i; j++)) is incorrect because it would only run i-1 times, producing patterns like '', '2', '33', '444' instead of '1', '22', '333', '4444'. To help students: Use trace tables to show how loop variables change and relate to output, and emphasize the importance of inclusive versus exclusive bounds. Practice generating various patterns to build intuition about loop relationships.

Question 17

Given the task requirements, how many iterations will occur with the given loop and input?

Problem description (Search Algorithm) A library app stores book IDs in a sorted int[] array. To quickly find a target ID, the program uses binary search with iteration (while) and selection (if/else if/else) to move the search bounds. On each loop, it computes mid and compares arr[mid] to target.

Task requirements

  • Use a while loop that continues while low <= high.
  • If arr[mid] == target, stop.
  • If arr[mid] < target, search right half; else search left half.

Constraints

  • 1n10001 \le n \le 1000
  • Array is sorted strictly increasing

Example Array: 1 4 7 9 12 15 20 Target: 12

Code snippet:

int[] arr = {1, 4, 7, 9, 12, 15, 20};
int target = 12;
int low = 0, high = arr.length - 1;
int count = 0;
while (low <= high) {
    count++;
    int mid = (low + high) / 2;
    if (arr[mid] == target) break;
    else if (arr[mid] < target) low = mid + 1;
    else high = mid - 1;
}
System.out.println(count);
  1. 2
  2. 3 (correct answer)
  3. 4
  4. 5

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on binary search iteration counting within Java coding tasks. Binary search repeatedly divides the search space in half, comparing the middle element with the target and adjusting bounds accordingly. In this scenario, searching for 12 in array {1, 4, 7, 9, 12, 15, 20}: iteration 1 checks mid=3 (value 9<12, adjust low), iteration 2 checks mid=5 (value 15>12, adjust high), iteration 3 checks mid=4 (value 12=12, found and break). Choice B is correct because the loop executes exactly 3 times before finding the target at index 4, with count incrementing at the start of each iteration before the break statement. Choice A is incorrect because it undercounts the iterations, not accounting for the final iteration where the target is found. To help students: Trace binary search step-by-step with diagrams showing low, high, and mid pointers at each iteration. Encourage students to track loop counters carefully, noting whether increments occur before or after condition checks and break statements.

Question 18

Given the task requirements, which of the following correctly implements the required loop structure?

Problem description (Search Algorithm) A Java program performs linear search on an int[] arr to find target. It must scan from left to right using iteration and use selection to stop early when the target is found. If found, print Found at index k; otherwise print Not found.

Input

  • Line 1: integer n
  • Line 2: n integers
  • Line 3: target

Output

  • Found at index k or Not found

Constraints

  • 1n2001 \le n \le 200
  • Values are integers in [1000,1000][-1000, 1000]

Choose the correct loop header/body pattern to scan all indices unless the target is found (assume foundIndex starts at -1).

  1. for (int i = 0; i < n && foundIndex == -1; i++) (correct answer)
  2. for (int i = 1; i <= n && foundIndex == -1; i++)
  3. for (int i = 0; i <= n && foundIndex == -1; i++)
  4. for (int i = n - 1; i >= 0 && foundIndex != -1; i--)

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on linear search with early termination conditions within Java coding tasks. Linear search examines array elements sequentially from index 0, stopping either when the target is found or all elements have been checked, requiring both proper bounds and a condition to detect early termination. In this scenario, the loop should continue while i < n (valid array indices) AND foundIndex == -1 (target not yet found), ensuring the search stops immediately upon finding the target. Choice A is correct because it combines the valid index range (i < n) with the early termination check (foundIndex == -1) using &&, properly implementing an efficient linear search that stops as soon as the target is located. Choice D is incorrect because it starts from the end and uses the wrong termination condition (foundIndex != -1), which would stop the loop when the target is NOT found rather than when it IS found. To help students: Trace through searches for elements at different positions (first, middle, last, not present) to understand early termination. Encourage students to think about the meaning of sentinel values like -1 and when loops should continue versus stop.

Question 19

Given the task requirements, which condition will correctly exit the while loop under described circumstances?

Problem description (Game Logic) A Java guessing game picks a secret integer from 1 to 100. The player has at most maxAttempts guesses. After each guess, the program prints feedback using selection:

  • if guess is too low: print Too low
  • else if guess is too high: print Too high
  • else: print Correct

The game uses iteration to repeatedly prompt until the player guesses correctly or runs out of attempts.

Input

  • Line 1: secret (for testing)
  • Line 2: maxAttempts
  • Next lines: guesses (one per line)

Output

  • Feedback after each guess
  • End message: Win if correct, otherwise Lose

Constraints

  • 1secret1001 \le secret \le 100
  • 1maxAttempts101 \le maxAttempts \le 10

Example Input: 42 3 10 50 42 Output: Too low Too high Correct Win

Loop skeleton:

int attempts = 0;
while (/* condition */) {
    // read guess, attempts++
    // print feedback
}
  1. attempts < maxAttempts && guess != secret (correct answer)
  2. attempts <= maxAttempts && guess == secret
  3. attempts < maxAttempts || guess != secret
  4. attempts <= maxAttempts || guess == secret

Explanation: This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on while loop conditions for a guessing game with attempt limits within Java coding tasks. A while loop should continue as long as the player hasn't guessed correctly AND hasn't exceeded the maximum attempts, using logical operators to combine these conditions. In this scenario, the loop must continue while attempts < maxAttempts (not exceeded limit) AND guess != secret (not guessed correctly), stopping when either condition becomes false. Choice A is correct because it uses && to ensure both conditions must be true for the loop to continue, properly implementing the game logic where the loop exits upon correct guess OR reaching the attempt limit. Choice C is incorrect because using || would continue the loop even after a correct guess if attempts remain, or after exceeding attempts if the guess is wrong, violating the game rules. To help students: Create truth tables for compound conditions and trace through specific scenarios like 'correct guess on attempt 2 of 3' or 'wrong guess on final attempt'. Emphasize that && requires both conditions true to continue, while || requires only one.