Implementing Selection and Iteration Algorithms
Help Questions
AP Computer Science A › Implementing Selection and Iteration Algorithms
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: $n$, then $n$ integers.
Output: sorted array.
Constraints: $1 \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<u>j</u> < a<u>min</u>) {
min = j;
}
}
int tmp = a<u>i</u>;
a<u>i</u> = a<u>min</u>;
a<u>min</u> = tmp;
}
System.out.print(a<u>0</u> + " " + a<u>1</u>);
1 2
1 5
5 2
2 1
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.
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$; 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);
cmd.equals('Q')
cmd != 'Q'
cmd == 'Q'
cmd = '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.
You are processing student grades. The program reads $n$ integer scores (0–100). It uses iteration to compute the average and selection to count how many are passing (>= 60). Input: first line $n$, second line has $n$ scores. Output: two lines: "avg: X" (double, one decimal) and "passing: Y". Constraints: $0 \le n \le 25$. If $n=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);
avg: NaN\npassing: 0
Runtime error (division by zero)
avg: 0.0\npassing: 0
avg: 0\npassing: 0
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.
You are implementing binary search for a library kiosk. The program reads a sorted array of $n$ 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 $n$, second line $n$ sorted integers, third line target. Output: index if found, else -1. Constraints: $1 \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<u>mid</u>) return mid;
else if (target < arr<u>mid</u>) {
// update here
} else {
low = mid + 1;
}
}
return -1;
low = mid;
high = mid + 1;
low = mid - 1;
high = mid - 1;
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.
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
GREENgo toYELLOW, afterYELLOWgo toRED, afterREDgo toGREEN. - Print one state per line for
stepsiterations.
Input
- One integer
steps
Output
stepslines of states
Constraints
- $1 \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";
}
GREEN, YELLOW, RED, YELLOW, GREEN
YELLOW, RED, GREEN, YELLOW, RED
GREEN, YELLOW, RED, GREEN, YELLOW
GREEN, RED, YELLOW, GREEN, RED
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.
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: $n$, then $n$ integers.
Output: the sorted array.
Constraints: $1 \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<u>i</u> and j = i - 1):
while (j>=0 && a[j]>key) { a[j]=a[j+1]; j--; }
while (j>=0 || a[j]>key) { a[j+1]=a[j]; j--; }
while (j>=0 && a[j]>key) { a[j+1]=a[j]; j--; }
while (j>0 && a[j]<key) { a[j+1]=a[j]; 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.
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 $\ge 90$:
A - else if score $\ge 80$:
B - else if score $\ge 70$:
C - else if score $\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
nlines: one integer score each
Output
nlines of letter grades- Final line:
Average: X
Constraints
- $0 \le n \le 30$
- Scores are integers in $0, 100$
- If
n == 0, print onlyAverage: 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<u>i</u>;
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));
B, F, A, then Average: 79
B, D, A, then Average: 79
A, F, B, then Average: 79
B, F, A, then Average: 80
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.
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: $n$, then $n$ sorted integers, then target.
Output: index of target or -1.
Constraints: $1 \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):
while (low <= high)
while (low == high)
while (low >= high)
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.
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
choiceis outside 1–5, printInvalidand prompt again. - Stop only when
choiceis valid.
Input
- A sequence of integers, one per prompt
Output
Invalidfor 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 */);
choice == 1 && choice == 5
choice < 1 && choice > 5
choice >= 1 && choice <= 5
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.
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: $n$, then $n$ integers, then target.
Output: the first index of target, or -1.
Constraints: $1 \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<u>i</u> == target) {
idx = i;
**break**;
}
}
System.out.print(idx);
-1
0
1
2
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.