Unit 2 Cycle 1 Day 27: Loop and Conditional Tracing

Unit 2 Foundation (Cycle 1) Day 27 of 28 Foundation

Loop and Conditional Tracing

Section Mixed — Review: All Unit 2

Key Concept

Combined loop and conditional tracing problems require you to track multiple variables through multiple iterations while evaluating conditions at each step. The most effective strategy is to create a trace table with columns for each variable and the loop condition, with one row per iteration. Include a column for any output produced. On the AP exam, these problems test patience and precision — the most common error is rushing through iterations and making arithmetic mistakes, not misunderstanding the concepts.

Consider the following code segment.

String s = "programming"; String result = ""; for (int i = 0; i < s.length(); i++) { String ch = s.substring(i, i + 1); if ("aeiou".indexOf(ch) >= 0) { result += ch; } } System.out.println(result);

What is printed as a result of executing the code segment?

Answer: (A) oai

The code extracts vowels from "programming": p(no) r(no) o(yes) g(no) r(no) a(yes) m(no) m(no) i(yes) n(no) g(no). Vowels in order: o, a, i. Result = "oai".

Why Not the Others?

(B) This would be the consonants (everything except vowels), which is the opposite of what the code selects.

(C) The vowels appear in the order they are found: o (index 2), a (index 5), i (index 8). Not sorted alphabetically.

(D) There are 3 vowels in "programming", not 2. The i at index 8 is also included.

Common Mistake

"aeiou".indexOf(ch) >= 0 checks if ch is a vowel by seeing if it exists in the vowel string. If indexOf returns -1, the character is not a vowel.

AP Exam Tip

Using indexOf to test membership in a set of characters is a common AP exam technique. If indexOf returns >= 0, the character is found in the test string.

Review this topic: Section Mixed — Review: All Unit 2 • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.