Question 1
What change would you make to the loop to sum only odd numbers instead of even numbers?
- Change i++ to i-- in the for loop.
- Change i < numbers.length to i <= numbers.length.
- Change % 2 == 0 to % 2 != 0 in the if.
- Change int i = 0 to int i = 1.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on modifying conditional logic. The modulo operator (%) returns the remainder of division, so n%2==0 tests if n is even (remainder 0 when divided by 2). To sum odd numbers instead of even, we need to check when n%2 equals 1 (or not equal to 0). Choice C is correct because changing % 2 == 0 to % 2 != 0 will make the condition true for odd numbers (1, 3, 5, etc.) instead of even numbers. Choice A would make the loop count backwards, Choice B would cause an array bounds error, and Choice D would skip the first element. To help students: Create truth tables for modulo expressions with various inputs. Practice rewriting conditions using both positive (==1) and negative (!=0) logic to reinforce understanding of boolean expressions.
Question 2
How does the initialization int i = 0 affect which array element is processed first?
- It starts with numbers[1] as the first element.
- It starts with numbers[0] as the first element.
- It starts with numbers[numbers.length] first.
- It starts with the last element in the array.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on array indexing and initialization. Arrays in Java are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. The initialization int i = 0 sets the starting value of the loop counter, determining which array element is accessed first. Choice B is correct because when i = 0, the expression numbers[i] accesses numbers[0], which is the first element in the array. Choice A incorrectly suggests starting at index 1 (the second element), while Choice C would cause an immediate ArrayIndexOutOfBoundsException. To help students: Use visual representations of arrays with labeled indices starting from 0. Practice converting between human counting (1st, 2nd, 3rd) and array indices (0, 1, 2) to prevent off-by-one errors.
Question 3
Refer to the code below. How does the condition in the loop affect its execution?
public class EvenSumBoundary {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4};
int evenSum = 0;
// Loop condition uses <= instead of <
for (int index = 0; index <= numbers.length - 1; index++) {
if (numbers[index] % 2 == 0) {
evenSum += numbers[index];
}
}
System.out.println("Even sum: " + evenSum);
}
}
- It iterates one fewer time than using index < length
- It iterates the same number of times as index < length
- It makes the loop infinite because index never changes
- It skips the last array element due to the condition
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on selection and iteration. For loops in Java repeat a block of code a specific number of times, using an initialization, a condition, and an increment/decrement statement. In this code snippet, the loop uses 'index <= numbers.length - 1', which is equivalent to 'index < numbers.length'. Choice B is correct because it iterates the same number of times, covering all elements. Choice A is incorrect due to misinterpreting the condition as stricter, a common mistake with boundary equivalents. To help students: Emphasize tracing loop execution with varied inputs. Encourage checking each component of the loop for common errors such as off-by-one mistakes or improper condition logic. Practice rewriting loops with equivalent while loops for deeper understanding.
Question 4
In the code below, how does the loop condition i < numbers.length affect the loop’s execution and output?
public class EvenSumDemo {
public static void main(String[] args) {
// Set up an array of integers to iterate over
int[] numbers = {1, 2, 3, 4};
// Track the sum of even values found in the array
int evenSum = 0;
// Iterate through each index in the array
for (int i = 0; i < numbers.length; i++) {
// Select only even numbers
if (numbers[i] % 2 == 0) {
evenSum += numbers[i];
}
}
// Output the final sum of even numbers
System.out.println("Even sum = " + evenSum);
}
}
- It skips index 0, so evenSum becomes 6.
- It repeats forever, so output never prints.
- It stops before last element, so evenSum becomes 2.
- It visits all indices, so evenSum becomes 6.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on loop conditions and array traversal. For loops in Java repeat a block of code a specific number of times, with the condition checked before each iteration to determine if the loop should continue. In this code snippet, the condition i < numbers.length ensures the loop visits every valid array index from 0 to 3, since the array has length 4. Choice D is correct because the loop starts at index 0 and continues while i is less than 4, visiting all indices (0, 1, 2, 3) and adding the even values 2 and 4 to get evenSum = 6. Choice C is incorrect because it misunderstands that i < numbers.length includes the last element at index 3, a common mistake when students confuse < with <=. To help students: Trace through loops step-by-step with index values and array contents visible. Emphasize that array indices run from 0 to length-1, making i < length the standard pattern for visiting all elements.
Question 5
In the code below, how does the condition i < numbers.length affect the search loop’s execution and output?
public class FindWithBreakDemo {
public static void main(String[] args) {
// Set up an array to search
int[] numbers = {4, 7, 9, 7};
// Target value to find
int target = 9;
// Track whether the target was found
boolean found = false;
// Search each index until the end of the array
for (int i = 0; i < numbers.length; i++) {
// If the target is found, record it and stop searching
if (numbers[i] == target) {
found = true;
break;
}
}
// Output the search result
System.out.println("Found = " + found);
}
}
- It skips index 0, so Found prints false.
- It checks all indices, so Found prints true.
- It runs one extra time, causing an error.
- It never becomes false, so Found never prints.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on search algorithms with early termination using break. For loops in Java can search through arrays and exit early when a target is found, improving efficiency. In this code snippet, the condition i < numbers.length ensures all array elements are checked until either the target is found or the array ends. Choice B is correct because the loop starts at index 0 and checks each element in [4, 7, 9, 7], finding the target value 9 at index 2, setting found to true, and breaking out of the loop, resulting in "Found = true" being printed. Choice A is incorrect because it misunderstands that the loop starts at index 0, not 1, checking all positions including the first element. To help students: Trace loops with break statements to show how they exit early. Compare search loops with and without break to understand efficiency benefits.
Question 6
Refer to the code below. Which part of the loop increments the loop counter?
public class EvenSumStepTwo {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4};
int evenSum = 0;
// Loop increments by 2 each iteration
for (int index = 0; index < numbers.length; index += 2) {
if (numbers[index] % 2 == 0) {
evenSum += numbers[index];
}
}
System.out.println("Even sum: " + evenSum);
}
}
- The initialization: int index = 0
- The update: index += 2
- The condition: index < numbers.length
- The selection: numbers[index] % 2 == 0
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on selection and iteration. For loops in Java repeat a block of code a specific number of times, using an initialization, a condition, and an increment/decrement statement. In this code snippet, the loop increments by 2 each time using 'index += 2'. Choice B is correct because the update 'index += 2' changes the counter by steps of 2. Choice D is incorrect due to confusing selection with update, a common mistake when the increment is non-standard. To help students: Emphasize tracing loop execution with varied inputs. Encourage checking each component of the loop for common errors such as off-by-one mistakes or improper condition logic. Practice rewriting loops with equivalent while loops for deeper understanding.
Question 7
Refer to the code below. How does the condition in the loop affect its execution?
public class EvenSumReverse {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4};
int evenSum = 0;
// Reverse traversal using decrement
for (int index = numbers.length - 1; index >= 0; index--) {
if (numbers[index] % 2 == 0) {
evenSum += numbers[index];
}
}
System.out.println("Even sum: " + evenSum);
}
}
- It stops when index becomes less than 0
- It stops when index becomes greater than 0
- It stops when evenSum becomes equal to 6
- It stops when index equals numbers.length
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on selection and iteration. For loops in Java repeat a block of code a specific number of times, using an initialization, a condition, and an increment/decrement statement. In this code snippet, the loop traverses the array in reverse from index 3 to 0, summing evens. Choice A is correct because the loop stops when 'index >= 0' becomes false, i.e., index < 0. Choice D is incorrect due to misunderstanding the condition for reverse loops, a common mistake confusing forward and reverse boundaries. To help students: Emphasize tracing loop execution with varied inputs. Encourage checking each component of the loop for common errors such as off-by-one mistakes or improper condition logic. Practice rewriting loops with equivalent while loops for deeper understanding.
Question 8
In the code below, which part of the for loop increments the loop counter each iteration?
public class EvenSumDemo {
public static void main(String[] args) {
// Set up an array of integers to iterate over
int[] numbers = {1, 2, 3, 4};
// Track the sum of even values found in the array
int evenSum = 0;
// Iterate through each index in the array
for (int i = 0; i < numbers.length; i++) {
// Select only even numbers
if (numbers[i] % 2 == 0) {
evenSum += numbers[i];
}
}
// Output the final sum of even numbers
System.out.println("Even sum = " + evenSum);
}
}
- The initialization: int i = 0
- The condition: i < numbers.length
- The update: i++
- The selection: numbers[i] % 2 == 0
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on identifying the three components of a for loop header. For loops in Java have three parts in parentheses: initialization (executed once), condition (checked before each iteration), and update (executed after each iteration). In this code snippet, the for loop header contains int i = 0 (initialization), i < numbers.length (condition), and i++ (update). Choice C is correct because i++ is the update expression that increments the loop counter after each iteration, moving from one array index to the next. Choice D is incorrect because numbers[i] % 2 == 0 is not part of the for loop header but rather a selection statement inside the loop body. To help students: Draw diagrams showing the three parts of a for loop header separated by semicolons. Practice identifying each component in various loops and explain when each executes during loop operation.
Question 9
Which part of the loop increments the loop counter in the code below?
- The statement: if (numbers[i] % 2 == 0).
- The expression: i++ in the for header.
- The initialization: int i = 0.
- The condition: i < numbers.length.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on the three components of a for loop header. A for loop has three parts: initialization (int i = 0), condition (i < numbers.length), and increment/update (i++). The increment statement i++ executes after each iteration of the loop body, increasing the loop counter by 1. Choice B is correct because i++ in the for header is specifically responsible for incrementing the loop counter after each iteration. Choice A refers to the if statement inside the loop body, which filters elements but doesn't affect the loop counter. To help students: Break down for loop syntax into its three components using parentheses or color coding. Demonstrate equivalent while loops to show when each part executes, reinforcing that the increment happens after the loop body.
Question 10
What change would you make to the loop to process the array from last index to first index?
- Use int i = numbers.length - 1; i >= 0; i--.
- Use int i = 0; i <= numbers.length; i++.
- Use int i = 1; i < numbers.length; i+=2.
- Use int i = numbers.length; i > 0; i++.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on reverse iteration through arrays. To process an array from last to first, we need to start at the highest valid index (length-1) and decrement until reaching 0. The loop must use i-- to move backwards and the condition i >= 0 to include index 0. Choice A is correct because it properly initializes i to numbers.length - 1 (last valid index), continues while i >= 0 (includes first element), and decrements with i--. Choice B would cause an array bounds error, Choice C skips elements, and Choice D has contradictory logic (i++ with i > 0 creates an infinite loop). To help students: Visualize array traversal with arrows showing direction. Practice converting between forward and backward loops, emphasizing the three changes needed: starting point, condition, and increment/decrement.
Question 11
How does changing the increment from i++ to i += 2 affect the loop’s logic?
- It visits only even indices, potentially skipping elements.
- It makes the loop infinite because i never changes.
- It causes the loop to start at index 2 automatically.
- It forces the if statement to always be true.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on modifying the increment statement. Changing i++ to i += 2 makes the loop counter increase by 2 each iteration instead of 1, causing the loop to skip every other index. Starting at i=0, the loop would visit indices 0, 2, 4, 6, etc., missing indices 1, 3, 5, etc. Choice A is correct because i += 2 visits only even indices (0, 2, 4...), potentially skipping half the array elements at odd indices. Choice B is incorrect as i does change (by 2 each time), and the loop will terminate when i exceeds the array length. To help students: Trace loops with different increments using tables showing which indices are visited. Practice with i += 2, i += 3, etc., to understand how step size affects which elements are processed in array traversal.
Question 12
In the code below, how does the loop condition i < numbers.length affect the loop’s execution?
- It skips odd values when adding to the sum.
- It initializes i to start at the first index.
- It stops before i reaches numbers.length.
- It increments i by 1 each iteration.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on loop conditions and array bounds. The loop condition i < numbers.length determines when the loop continues executing - it runs while i is less than the array length. This condition ensures the loop stops before attempting to access an index that doesn't exist (array indices run from 0 to length-1). Choice C is correct because it accurately describes that the loop stops before i reaches numbers.length, preventing an ArrayIndexOutOfBoundsException. Choice A is incorrect as the condition doesn't affect which values are processed, only how many iterations occur. To help students: Draw diagrams showing array indices and trace through loops step-by-step. Emphasize that arrays are zero-indexed, so valid indices range from 0 to length-1, making the condition i < length essential for safe array traversal.
Question 13
How does the condition inside the loop body determine whether a value contributes to the sum?
- It adds every element because the if is always true.
- It adds an element only when numbers[i] is even.
- It adds an element only when i is even.
- It adds an element only when numbers.length is even.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on conditional statements within loop bodies. The if statement inside the loop acts as a filter, determining which array elements contribute to the sum based on a specific criterion. The condition numbers[i] % 2 == 0 checks if the current array element (not the index) is even by testing if it's divisible by 2 with no remainder. Choice B is correct because it accurately states that elements are added to sum only when numbers[i] (the value at index i) is even. Choice C incorrectly focuses on the index i rather than the array value, a common conceptual error. To help students: Distinguish between loop counters (i) and array values (numbers[i]) using different colors or notation. Practice writing conditions that test array values versus indices to reinforce this critical distinction.
Question 14
In the code below, which part of the for loop increments the index during the array search?
public class FindWithBreakDemo {
public static void main(String[] args) {
// Set up an array to search
int[] numbers = {4, 7, 9, 7};
// Target value to find
int target = 9;
// Track whether the target was found
boolean found = false;
// Search each index until the end of the array
for (int i = 0; i < numbers.length; i++) {
// If the target is found, record it and stop searching
if (numbers[i] == target) {
found = true;
break;
}
}
// Output the search result
System.out.println("Found = " + found);
}
}
- The initialization: int i = 0
- The condition: i < numbers.length
- The update: i++
- The selection: numbers[i] == target
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on identifying loop components in search algorithms. For loops in Java maintain consistent structure even when implementing algorithms like linear search with early termination. In this code snippet, the for loop uses the standard three components to traverse the array while searching for a target value. Choice C is correct because i++ is the update expression that increments the index after each iteration, allowing the search to progress through consecutive array positions. Choice D is incorrect because numbers[i] == target is the selection condition inside the loop body that determines if the target is found, not part of the for loop header. To help students: Emphasize that loop structure remains constant across different algorithms. Practice identifying loop components in various contexts like searching, filtering, and accumulating.
Question 15
Using the code below, what is the output of the loop given the list ["cat","car","dog","cart"]?
import java.util.ArrayList;
public class PatternPrintDemo {
public static void main(String[] args) {
// Set up a collection of strings to iterate over
ArrayList<String> words = new ArrayList<String>();
words.add("cat");
words.add("car");
words.add("dog");
words.add("cart");
// Traverse the list by index
for (int i = 0; i < words.size(); i++) {
// Select only strings that start with "car"
if (words.get(i).startsWith("car")) {
System.out.println(words.get(i));
}
}
}
}
- cat then car then dog then cart
- car then cart
- cart only
- car only
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on tracing execution with string methods and selection. For loops in Java can process collections while using string methods to filter output based on specific patterns. In this code snippet, the loop examines each string in the ArrayList ["cat", "car", "dog", "cart"], using startsWith("car") to select matching strings. Choice B is correct because the loop finds two strings that start with "car": "car" at index 1 and "cart" at index 3, printing them in that order on separate lines. Choice C is incorrect because it suggests only the last matching item prints, misunderstanding that the loop prints each match as it's found. To help students: Create visual traces showing which strings match the condition at each iteration. Practice with various string methods and patterns to build pattern-matching intuition.
Question 16
In the code below, which part of the for loop increments the index used to traverse the ArrayList?
import java.util.ArrayList;
public class PatternPrintDemo {
public static void main(String[] args) {
// Set up a collection of strings to iterate over
ArrayList<String> words = new ArrayList<String>();
words.add("cat");
words.add("car");
words.add("dog");
words.add("cart");
// Traverse the list by index
for (int i = 0; i < words.size(); i++) {
// Select only strings that start with "car"
if (words.get(i).startsWith("car")) {
System.out.println(words.get(i));
}
}
}
}
- The update: i++
- The initialization: int i = 0
- The condition: i < words.size()
- The selection: startsWith("car")
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on identifying loop components when working with ArrayLists. For loops in Java maintain the same three-part structure whether traversing arrays or ArrayLists: initialization, condition, and update. In this code snippet, the for loop uses int i = 0 to initialize, i < words.size() as the condition, and i++ to increment the index. Choice A is correct because i++ is the update expression that increments the index variable after each iteration, allowing the loop to move through consecutive ArrayList positions. Choice D is incorrect because startsWith("car") is a method call within the loop body's selection statement, not part of the for loop header structure. To help students: Compare array and ArrayList loop syntax side-by-side to show similarities. Highlight that the loop structure remains constant regardless of the data structure being traversed.
Question 17
In the code below, how does the loop condition i < words.size() affect its execution and printed output?
import java.util.ArrayList;
public class PatternPrintDemo {
public static void main(String[] args) {
// Set up a collection of strings to iterate over
ArrayList<String> words = new ArrayList<String>();
words.add("cat");
words.add("car");
words.add("dog");
words.add("cart");
// Traverse the list by index
for (int i = 0; i < words.size(); i++) {
// Select only strings that start with "car"
if (words.get(i).startsWith("car")) {
System.out.println(words.get(i));
}
}
}
}
- It skips the last word, printing only car.
- It prints car and cart, then stops.
- It runs one extra time, causing an error.
- It starts at index 1, printing dog and cart.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on ArrayList traversal and string selection. For loops in Java can iterate through collections using index-based access, with the condition determining how many elements are visited. In this code snippet, the condition i < words.size() ensures the loop visits all valid indices from 0 to 3 in the ArrayList containing ["cat", "car", "dog", "cart"]. Choice B is correct because the loop checks all four words, finds that "car" (index 1) and "cart" (index 3) start with "car", prints both in order, then stops normally after checking all elements. Choice A is incorrect because it misunderstands that i < words.size() includes the last element at index 3, similar to array traversal. To help students: Emphasize that ArrayList indices work like array indices, from 0 to size()-1. Practice tracing loops with different string methods like startsWith(), contains(), and equals().
Question 18
In the code below, what change would you make to the loop to sum only odd numbers instead?
public class EvenSumDemo {
public static void main(String[] args) {
// Set up an array of integers to iterate over
int[] numbers = {1, 2, 3, 4};
// Track the sum of even values found in the array
int evenSum = 0;
// Iterate through each index in the array
for (int i = 0; i < numbers.length; i++) {
// Select only even numbers
if (numbers[i] % 2 == 0) {
evenSum += numbers[i];
}
}
// Output the final sum of even numbers
System.out.println("Even sum = " + evenSum);
}
}
- Change i++ to i += 2 in the update.
- Change i < numbers.length to i <= numbers.length.
- Change numbers[i] % 2 == 0 to numbers[i] % 2 != 0.
- Change int i = 0 to int i = 1 only.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on modifying selection conditions within loops. For loops in Java can contain conditional statements that filter which elements to process based on specific criteria. In this code snippet, the condition numbers[i] % 2 == 0 selects even numbers by checking if the remainder when divided by 2 equals zero. Choice C is correct because changing the condition to numbers[i] % 2 != 0 would select odd numbers instead, since odd numbers have a remainder of 1 when divided by 2. Choice A is incorrect because changing the update to i += 2 would skip every other element in the array, missing some numbers entirely rather than changing the selection criteria. To help students: Review the modulo operator and how it identifies even (% 2 == 0) versus odd (% 2 != 0) numbers. Practice modifying different parts of loops to understand how each change affects the output.
Question 19
In the code below, what change would you make to print only words containing "ar" anywhere in the string?
import java.util.ArrayList;
public class PatternPrintDemo {
public static void main(String[] args) {
// Set up a collection of strings to iterate over
ArrayList<String> words = new ArrayList<String>();
words.add("cat");
words.add("car");
words.add("dog");
words.add("cart");
// Traverse the list by index
for (int i = 0; i < words.size(); i++) {
// Select only strings that start with "car"
if (words.get(i).startsWith("car")) {
System.out.println(words.get(i));
}
}
}
}
- Replace startsWith("car") with contains("ar").
- Replace i++ with i += 2 to skip items.
- Replace i < words.size() with i <= words.size().
- Replace int i = 0 with int i = 1 only.
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on modifying string selection criteria within loops. For loops in Java can use different string methods to change which elements are selected for processing. In this code snippet, startsWith("car") checks if strings begin with a specific prefix, selecting "car" and "cart" from the list. Choice A is correct because replacing startsWith("car") with contains("ar") would select any string containing "ar" anywhere within it, which would match "car" and "cart" (both contain "ar"). Choice B is incorrect because changing the increment to i += 2 would skip elements at odd indices, potentially missing strings that should be printed. To help students: Review common string methods like startsWith(), endsWith(), contains(), and equals(). Create exercises where students predict output after modifying selection conditions.
Question 20
Using the code below, what is the output of the loop if the input array is [1, 2, 3, 4]?
public class EvenSumDemo {
public static void main(String[] args) {
// Set up an array of integers to iterate over
int[] numbers = {1, 2, 3, 4};
// Track the sum of even values found in the array
int evenSum = 0;
// Iterate through each index in the array
for (int i = 0; i < numbers.length; i++) {
// Select only even numbers
if (numbers[i] % 2 == 0) {
evenSum += numbers[i];
}
}
// Output the final sum of even numbers
System.out.println("Even sum = " + evenSum);
}
}
- Even sum = 10
- Even sum = 6
- Even sum = 4
- Even sum = 0
Explanation: This question tests AP Computer Science A understanding of for loops, focusing on tracing loop execution with selection statements. For loops in Java iterate through a sequence while evaluating conditions to selectively process elements. In this code snippet, the loop examines each element in [1, 2, 3, 4], checking if it's even using the modulo operator, and accumulating even values. Choice B is correct because the loop finds two even numbers (2 and 4) and adds them together: evenSum = 0 + 2 + 4 = 6, then prints "Even sum = 6". Choice A is incorrect because it represents the sum of all array elements (1+2+3+4=10), showing a misunderstanding of the selection condition that filters for even numbers only. To help students: Create trace tables showing i, numbers[i], the condition result, and evenSum after each iteration. Practice with different arrays and conditions to reinforce how selection inside loops affects the final result.