What this quiz covers
This quiz focuses on Algorithms With Selection And Repetition, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
A mail-sorting machine processes a stack of letters. For each letter, it reads the ZIP code. If the ZIP code is for the local area, the letter is placed in Bin A. Otherwise, it is placed in Bin B. This process continues until the stack is empty. This algorithm combines which two fundamental concepts?
AP Computer Science a Quiz
Practice Algorithms With Selection And Repetition 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.
This quiz focuses on Algorithms With Selection And Repetition, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
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.
A mail-sorting machine processes a stack of letters. For each letter, it reads the ZIP code. If the ZIP code is for the local area, the letter is placed in Bin A. Otherwise, it is placed in Bin B. This process continues until the stack is empty. This algorithm combines which two fundamental concepts?
Explanation: The process is performed "for each letter" until the stack is empty, which is repetition. Inside that repetition, a decision is made based on the ZIP code ("If the ZIP code is..."), which is selection. Therefore, the algorithm's main structure combines repetition and selection.
A process for grading an essay is described as: "Read the entire essay from beginning to end. If the essay contains any spelling errors, deduct 5 points from the total score." Which combination of algorithmic concepts is represented?
Explanation: "Read the entire essay" is the first step in a sequence. "If the essay contains any spelling errors, deduct 5 points" is a single decision based on a condition, which is selection. The process does not describe repeating any action in a loop structure. Therefore, it is a sequence followed by a selection.
An algorithm is represented by a diagram starting with a rectangular box labeled "Get user input". An arrow points to a diamond-shaped box labeled "Is input valid?". The "No" arrow from the diamond points back to the "Get user input" box. The "Yes" arrow points to a box labeled "Process data". This diagram illustrates which fundamental algorithmic structure?
Explanation: The diagram shows a loop. If the input is not valid, the process returns to getting input again. This is repetition. The diamond shape represents the decision that controls the loop. Therefore, the structure is a repetition loop designed to validate user input.
An algorithm for a thermostat is described as follows: "Repeatedly check the room temperature. As long as the temperature is below 68 degrees, the heat should remain on." Which algorithmic building block is primarily used in this description?
Explanation: The process involves "repeatedly" checking and performing an action "as long as" a condition is true. This is the definition of repetition, or a loop. Choice (B) is incorrect because the check is continuous, not a one-time decision. While sequencing (C) is a component of the process, the overarching structure that defines the algorithm is repetition. Data abstraction (D) is a valid concept but does not describe the algorithmic structure.
A traffic light cycles through GREEN, YELLOW, RED for a fixed number of cycles. Inputs are cycles and starting state; output is the printed sequence of states. Example input: cycles 1, start GREEN; output: GREEN, YELLOW, RED. Example input: cycles 2, start RED; output: RED, GREEN, YELLOW, RED, GREEN, YELLOW.
String state = startState;
for (int c = 0; c < cycles; c++) {
for (int t = 0; t < 3; t++) {
System.out.println(state);
if (state.equals("GREEN")) state = "YELLOW";
else if (state.equals("YELLOW")) state = "RED";
else state = "GREEN";
}
}
Consider the algorithm for the traffic light; what is the time complexity in terms of cycles c?
Explanation: This question tests AP Computer Science A skills: understanding algorithms with selection and repetition, specifically analyzing time complexity of nested loops. Time complexity measures how execution time grows with input size, and nested loops often multiply their iteration counts. In this traffic light algorithm, the outer loop runs 'cycles' times, and the inner loop always runs exactly 3 times (once for each light state). Choice B is correct because the inner loop has constant size (3 iterations), making the total iterations 3c, which simplifies to O(c) linear time complexity. Choice C is incorrect because two loops don't always imply quadratic time - it depends on whether both loops scale with input size. To help students: Emphasize that constant-size inner loops don't change the order of growth. Practice calculating iterations by multiplying loop counts and identifying which variables affect runtime.
A traffic light simulation prints states for a total duration in seconds, changing every 5 seconds. Inputs are totalSeconds and startState; output is the printed state at each second. Example input: total 6, start GREEN; output: GREEN printed 5 times, then YELLOW once. Example input: total 5, start RED; output: RED printed 5 times.
String state = startState;
for (int s = 1; s <= totalSeconds; s++) {
System.out.println(state);
if (s % 5 == 0) {
if (state.equals("GREEN")) state = "YELLOW";
else if (state.equals("YELLOW")) state = "RED";
else state = "GREEN";
}
}
Consider the algorithm for the traffic light; what is the output after totalSeconds = 5, startState = GREEN?
Explanation: This question tests AP Computer Science A skills: understanding algorithms with selection and repetition, focusing on modulo operations for periodic events. The modulo operator (%) helps detect when counters reach specific intervals, useful for implementing timed state changes. In this traffic light simulation, the condition 's % 5 == 0' triggers state changes every 5 seconds, but the state change occurs after printing the current state. Choice B is correct because GREEN is printed 5 times (when s = 1, 2, 3, 4, 5), then the state changes to YELLOW after the 5th print when s % 5 == 0 evaluates to true. Choice A is incorrect because it miscounts - GREEN is printed 5 times, not 4. To help students: Emphasize that loop body execution order matters - printing happens before the state change check. Practice tracing loops with modulo conditions to understand periodic behavior.
A school processes grades to compute average, but must ignore any negative entries as invalid. Inputs are gradeList; outputs are average of valid grades and validCount. Example input: [90, -1, 80]; output: average 85.0, validCount 2. Example input: [-5, -2]; output: validCount 0.
int sum = 0;
int validCount = 0;
for (int i = 0; i < gradeList.length; i++) {
if (gradeList[i] >= 0) {
sum += gradeList[i];
validCount++;
}
}
double average = (validCount == 0) ? 0.0 : (double) sum / validCount;
System.out.println(average + "," + validCount);
Consider the algorithm for grade processing; how would you modify the algorithm to also count grades above a threshold efficiently?
Explanation: This question tests AP Computer Science A skills: understanding algorithms with selection and repetition, focusing on efficient algorithm modification. Efficient algorithms minimize redundant operations by combining related tasks within existing loops rather than creating additional passes through data. To count grades above a threshold while already iterating through the array, the most efficient approach is to add the counting logic within the existing loop. Choice B is correct because adding an if statement inside the existing loop to increment countAbove allows both tasks (summing valid grades and counting above-threshold grades) to be accomplished in a single pass through the data. Choice A is incorrect because adding a second full loop would double the time complexity unnecessarily. To help students: Emphasize the efficiency gained by combining related operations in a single loop. Practice identifying opportunities to merge similar tasks that process the same data.
A chef is following a recipe to bake a cake. One step in the recipe reads, "If the batter is too thick, add one tablespoon of milk." Which fundamental algorithmic concept does this step best illustrate?
Explanation: The step involves making a choice (to add milk or not) based on a condition (the batter's thickness). This is the definition of selection. While the step is part of a larger sequence (A), the core concept illustrated within the step is selection. The instruction is a one-time check, not a loop, so it is not repetition (C). Abstraction (D) is a broader concept; the most precise answer is selection.
Consider an algorithm for finding a specific name in a printed, alphabetized phone book. The process is as follows: 1. Open the book to the middle. 2. If the desired name is on that page, stop. 3. If the name comes alphabetically before the names on the page, repeat the process with the first half of the book. 4. Otherwise, repeat the process with the second half of the book. This entire process is an example of which combination of algorithmic concepts?
Explanation: The overall process is repeated ("repeat the process..."), making it a form of repetition. Within each repetition, a choice is made (go to the first half, second half, or stop) based on comparing the names, which is selection. Therefore, the algorithm is best described as a repetition structure that contains selection logic to guide the next step.
Consider the following description of an algorithm for an automated car wash:
The car enters the wash bay.
The system checks if the customer selected the "undercarriage spray" option.
If the option was selected, the undercarriage spray is activated.
The car moves forward on the conveyor belt.
For each of the three washing stations (soap, rinse, wax), the car pauses and the station's function is performed.
Which part of this algorithm best demonstrates the concept of repetition?
Explanation: Step 5 describes performing a similar action (pausing and applying a treatment) for a set of items (the three stations). This is a form of repetition, equivalent to a fixed loop that executes three times. Step 2 (and 3) describes selection (B). The other actions are part of the overall sequence (A, D).
An algorithm is designed to process a list of exam scores. It is intended to count how many scores are 90 or above. Which of the following describes the necessary combination of algorithmic building blocks for this task?
Explanation: To solve the problem, the algorithm must look at every score, which requires repetition (a loop). For each score, it must make a decision: is this score 90 or greater? This requires selection (an if-statement). Both are essential. The other options are incomplete because they omit one of the necessary components.
An algorithm for managing an alarm clock is described: "1. If it is a weekday, set the alarm for 6:30 AM. 2. Then, wait until the alarm time is reached. 3. When the alarm sounds, repeatedly play the alarm sound until the snooze button is pressed." Which statement accurately identifies the algorithmic concepts used?
Explanation: Step 1 ("If it is a weekday...") is a decision based on a condition, which is selection. Step 3 ("...repeatedly play the alarm sound until...") is an action that is repeated based on a condition, which is repetition. These steps occur in a specific order, which is sequencing. Therefore, the algorithm combines all three concepts.
An algorithm for a simple game is as follows: A player starts with 10 points. The player repeatedly rolls a die. If the die shows a 6, the player gains a point. If the die shows a 1, the player loses a point. The game ends when the player runs out of points. Which of the following building blocks are all present in this algorithm?
Explanation: The algorithm has a clear order of operations (sequencing). It involves repeatedly rolling a die until a condition is met (repetition). Within each roll, it makes a decision based on the number rolled (selection). Therefore, all three fundamental building blocks are present.
Consider two algorithms for approving a loan application.
How does the order of the algorithmic components potentially cause these algorithms to have different outcomes or efficiencies?
Explanation: Both algorithms use two selection steps within a sequence. However, the order of these steps is different. An applicant could be rejected by the first check in Algorithm X (low credit score) but pass the first check in Algorithm Y (high income). This change in sequence can affect when an application is rejected, impacting efficiency. Both algorithms are logically valid, just structured differently.
An algorithm for making a custom pizza is described:
Start with a pizza base.
Check if the customer wants tomato sauce. If yes, add it.
Check if the customer wants pesto sauce. If yes, add it.
Repeat the following for every topping the customer selected: add the topping to the pizza.
Bake the pizza.
Which statement best describes the use of selection and repetition in this algorithm?
Explanation: Steps 2 and 3 involve making a decision to perform a single action based on a condition ("if the customer wants..."), which is selection. Step 4 involves performing an action for a list of items ("for every topping..."), which is repetition.
A student is writing an algorithm to simulate a soccer penalty shootout. The shootout continues with additional rounds as long as the score is tied after the initial five rounds. Which algorithmic concept is best represented by the rule for additional rounds?
Explanation: The phrase "continues with additional rounds as long as" indicates a loop or repetition. The shootout process is repeated until the condition (a tied score) is no longer true. This is a clear example of repetition controlling the flow of the algorithm.
An algorithm is designed to check if a password meets complexity requirements. It must perform three checks: "Does it have at least 8 characters?", "Does it contain a number?", and "Does it contain a special character?". The password is valid only if all three checks pass. Which statement best describes the logical structure required?
Explanation: The core of this algorithm is making decisions. It must check three conditions and act based on whether all are true. This is a selection structure, likely implemented with if statements and logical AND operators. Choice (A) is incorrect as there is no looping or repetition. Choice (B) is incorrect because decisions are central to the process. Choice (D) describes the wrong logic (an OR condition instead of an AND condition).
Consider an algorithm for withdrawing money from an ATM: 1. Insert card. 2. Enter PIN. 3. If PIN is correct, display transaction options. 4. Select withdrawal amount. 5. If account balance is sufficient, dispense cash. 6. Eject card. The step "If account balance is sufficient, dispense cash" is an example of what?
Explanation: This step describes a decision point. The action of dispensing cash is conditional upon the account balance. This is a clear example of selection. While it is part of a sequence (B) and uses data that could be considered a form of input (D), the core algorithmic concept being illustrated by the "if...then" structure is selection.
A manufacturing robot's algorithm is to pick up a part, check it for defects, and if it has no defects, place it on a conveyor belt. The robot is instructed to perform this entire process for a batch of 100 parts. Which statement accurately describes the algorithm's structure?
Explanation: The overall process is repeated 100 times, making repetition the outer structure. Within each repetition, the robot performs a check ("check it for defects") and makes a decision, which is selection. Therefore, the algorithm is best described as a selection nested within a repetition.
A school stores grades in an int[] gradeList; the algorithm iterates to compute average and count grades >= threshold. Inputs are gradeList and threshold; outputs are average and countAbove. Example input: [80, 90, 70], threshold 85; output: average 80.0, countAbove 1. Example input: [100, 60], threshold 70; output: average 80.0, countAbove 1.
// Compute average and count grades at or above threshold
int sum = 0;
int countAbove = 0;
for (int i = 0; i < gradeList.length; i++) {
sum += gradeList[i];
if (gradeList[i] >= threshold) {
countAbove++;
}
}
double average = (double) sum / gradeList.length;
System.out.println(average + "," + countAbove);
Consider the algorithm for processing grades; which part ensures every grade is compared to threshold exactly once?
Explanation: This question tests AP Computer Science A skills: understanding algorithms with selection and repetition, focusing on loop control and iteration mechanics. The for-loop structure ensures systematic traversal through arrays by using an index variable that increments from 0 to the array length minus one. In this problem, the for-loop header 'for (int i = 0; i < gradeList.length; i++)' controls the iteration, visiting each array element exactly once. Choice B is correct because the loop header specifically iterates once per index in gradeList, ensuring every grade is accessed through gradeList[i] and compared to the threshold exactly once. Choice A is incorrect because the cast to double only affects the average calculation, not the iteration count. To help students: Emphasize that for-loop headers control iteration count, not the loop body. Practice tracing through loops with index variables to see how each element is accessed exactly once.