AP Computer Science a Quiz: For Loops
20 questions · exam conditions
0:00
For LoopsQuestion 1 of 20

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
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: For Loops

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

What this quiz covers

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

How to use this quiz

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

All questions

Question 1

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);
    }
}
  1. It iterates one fewer time than using index < length
  2. It iterates the same number of times as index < length (correct answer)
  3. It makes the loop infinite because index never changes
  4. 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 2

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);
    }
}
  1. It skips index 0, so evenSum becomes 6.
  2. It repeats forever, so output never prints.
  3. It stops before last element, so evenSum becomes 2.
  4. It visits all indices, so evenSum becomes 6. (correct answer)

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 3

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);
    }
}
  1. It skips index 0, so Found prints false.
  2. It checks all indices, so Found prints true. (correct answer)
  3. It runs one extra time, causing an error.
  4. 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 4

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);
    }
}
  1. The initialization: int index = 0
  2. The update: index += 2 (correct answer)
  3. The condition: index < numbers.length
  4. 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 5

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);
    }
}
  1. It stops when index becomes less than 0 (correct answer)
  2. It stops when index becomes greater than 0
  3. It stops when evenSum becomes equal to 6
  4. 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 6

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);
    }
}
  1. The initialization: int i = 0
  2. The condition: i < numbers.length
  3. The update: i++ (correct answer)
  4. 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 7

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);
    }
}
  1. The initialization: int i = 0
  2. The condition: i < numbers.length
  3. The update: i++ (correct answer)
  4. 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 8

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));
            }
        }
    }
}
  1. cat then car then dog then cart
  2. car then cart (correct answer)
  3. cart only
  4. 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 9

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));
            }
        }
    }
}
  1. The update: i++ (correct answer)
  2. The initialization: int i = 0
  3. The condition: i < words.size()
  4. 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 10

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));
            }
        }
    }
}
  1. It skips the last word, printing only car.
  2. It prints car and cart, then stops. (correct answer)
  3. It runs one extra time, causing an error.
  4. 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 11

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);
    }
}
  1. Change i++ to i += 2 in the update.
  2. Change i < numbers.length to i <= numbers.length.
  3. Change numbers[i] % 2 == 0 to numbers[i] % 2 != 0. (correct answer)
  4. 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 12

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));
            }
        }
    }
}
  1. Replace startsWith("car") with contains("ar"). (correct answer)
  2. Replace i++ with i += 2 to skip items.
  3. Replace i < words.size() with i <= words.size().
  4. 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 13

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);
    }
}
  1. Even sum = 10
  2. Even sum = 6 (correct answer)
  3. Even sum = 4
  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.

Question 14

Refer to the code below. What is the output of the loop if the input array is [1, 2, 3, 4]?

public class EvenSumExample {
    public static void main(String[] args) {
        // Input array to iterate over
        int[] numbers = {1, 2, 3, 4};

        // Accumulator for the sum of even numbers
        int evenSum = 0;

        // For loop: initialize index, test condition, then increment index
        for (int index = 0; index < numbers.length; index++) {
            // Selection: only add even values
            if (numbers[index] % 2 == 0) {
                evenSum += numbers[index];
            }
        }

        // Output the computed sum
        System.out.println("Even sum: " + evenSum);
    }
}
  1. Even sum: 4
  2. Even sum: 6 (correct answer)
  3. Even sum: 10
  4. Even sum: 2

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 iterates over an array [1, 2, 3, 4], checking each element with a conditional statement to sum only even numbers. Choice B is correct because the even numbers 2 and 4 sum to 6, matching the output 'Even sum: 6'. Choice C is incorrect due to a misunderstanding of the selection logic, a common mistake where students might sum all numbers instead of only evens. 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.

Question 15

Refer to the code below. How does the condition in the loop affect its execution?

public class EvenSumExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4};
        int evenSum = 0;

        for (int index = 0; index < numbers.length; index++) {
            if (numbers[index] % 2 == 0) {
                evenSum += numbers[index];
            }
        }

        System.out.println("Even sum: " + evenSum);
    }
}
  1. It repeats while index is less than the array length (correct answer)
  2. It repeats while index is less than the last element value
  3. It repeats until evenSum becomes greater than 0
  4. It repeats while index is less than or equal to the 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 iterates over an array while the index is less than the array length, summing even numbers. Choice A is correct because the condition ensures the loop repeats exactly for each array element without going out of bounds. Choice D is incorrect due to a misunderstanding of the loop's stopping condition, a common mistake when students confuse '<' with '<=' and risk index out-of-bounds errors. 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 16

Refer to the code below. What change would you make to the loop to sum only odd numbers?

public class EvenSumExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4};
        int evenSum = 0;

        for (int index = 0; index < numbers.length; index++) {
            if (numbers[index] % 2 == 0) {
                evenSum += numbers[index];
            }
        }

        System.out.println("Even sum: " + evenSum);
    }
}
  1. Change index++ to index-- in the for loop
  2. Change index < numbers.length to index <= numbers.length
  3. Change the if test to numbers[index] % 2 != 0 (correct answer)
  4. Change evenSum to start at 1 instead of 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 iterates over an array, using a conditional to sum even numbers, which can be modified for odds. Choice C is correct because changing the if test to 'numbers[index] % 2 != 0' selects odd numbers instead. Choice A is incorrect due to reversing the loop direction, a common mistake that would cause an infinite loop or errors without adjusting other parts. 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 17

Refer to the code below. What is the output of the loop if the input array is [1, 2, 3, 4]?

public class EvenSumVariant {
    public static void main(String[] args) {
        // Input array to iterate over
        int[] numbers = {1, 2, 3, 4};

        // Accumulator for the sum of even numbers
        int evenSum = 0;

        // For loop with a different starting index
        for (int index = 1; index < numbers.length; index++) {
            // Selection: only add even values
            if (numbers[index] % 2 == 0) {
                evenSum += numbers[index];
            }
        }

        // Output the computed sum
        System.out.println("Even sum: " + evenSum);
    }
}
  1. Even sum: 6 (correct answer)
  2. Even sum: 2
  3. Even sum: 0
  4. Even sum: 4

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 starts from index 1, iterating over [2, 3, 4] and summing evens 2 and 4. Choice A is correct because the sum is 6, skipping the first odd element. Choice C is incorrect due to assuming no evens are summed, a common mistake if students forget the starting index change. 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.

Question 18

Refer to the code below. What is the output of the loop if the input array is [1, 2, 3, 4]?

public class EvenSumStepTwo {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4};
        int evenSum = 0;

        // Visit every other index: 0, 2, ...
        for (int index = 0; index < numbers.length; index += 2) {
            if (numbers[index] % 2 == 0) {
                evenSum += numbers[index];
            }
        }

        System.out.println("Even sum: " + evenSum);
    }
}
  1. Even sum: 0 (correct answer)
  2. Even sum: 2
  3. Even sum: 6
  4. Even sum: 4

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 visits indices 0 and 2 ([1, 3]), both odd, so no evens are summed. Choice A is correct because the sum remains 0. Choice C is incorrect due to assuming all evens are summed, a common mistake ignoring the step increment. 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.

Question 19

What change would you make to the loop to sum only odd numbers instead of even numbers?

  1. Change i++ to i-- in the for loop.
  2. Change i < numbers.length to i <= numbers.length.
  3. Change % 2 == 0 to % 2 != 0 in the if. (correct answer)
  4. 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 20

How does the initialization int i = 0 affect which array element is processed first?

  1. It starts with numbers[1] as the first element.
  2. It starts with numbers[0] as the first element. (correct answer)
  3. It starts with numbers[numbers.length] first.
  4. 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.