Unit 2 Cycle 2 Day 27: Complex Conditional and Loop Interaction

Unit 2 Advanced (Cycle 2) Day 27 of 28 Advanced

Complex Conditional and Loop Interaction

Section Mixed — Review: All Unit 2

Key Concept

Advanced combined problems integrate everything from Unit 2: nested conditionals with compound boolean expressions inside nested loops that process strings. The AP exam's most challenging Unit 2 questions require tracking 4-5 variables simultaneously through nested iteration with branching logic. The key to success is maintaining a disciplined trace table and not taking shortcuts. Each line of code must be evaluated with the current variable values, not with assumed or estimated values.

Consider the following code segment.

int result = 0; for (int i = 1; i <= 5; i++) { if (i % 2 != 0) { result += i; } else { result -= i; } } System.out.println(result);

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

Answer: (A) 3

i=1(odd): result=0+1=1. i=2(even): result=1-2=-1. i=3(odd): result=-1+3=2. i=4(even): result=2-4=-2. i=5(odd): result=-2+5=3.

Why Not the Others?

(B) The alternating pattern adds odd numbers and subtracts even: 1-2+3-4+5 = 3, not -3.

(C) 15 would be the sum without any subtraction (1+2+3+4+5).

(D) 1 would be the result of a different alternating pattern.

Common Mistake

When a loop alternates between addition and subtraction based on even/odd, trace each iteration. The sign alternates: +1, -2, +3, -4, +5 = 3.

AP Exam Tip

For alternating-operation loops, write out each term with its sign before computing. This prevents sign errors.

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.