Nested if Statements
Part of: Boolean Expressions & if Statements
What Is Nesting? A nested if is an if statement placed inside the body of another if (or else). Nesting lets you refine a decision in stages: the inner condition is only checked when the outer condition is already true. Here the member check happens only for adults. A minor never reaches the inner test. Nesting vs Compound Conditions Many nested structures can be rewritten with logical operators. The two adult outcomes above could partly use &&: Use nesting when different outer branches need different follow-up logic; use a compound condition when you simply need several things true at once. Choosing the clearer form is a judgment call the AP exam rewards. The Dangling else Problem When braces are omitted, an else attaches to the nearest unmatched if , not by indentation. This is the dangling else : The else belongs to if (b), even though indentation might suggest otherwise. Always use braces to make the pairing explicit and avoid this classic bug. Readability Deeply nested ifs become hard to follow. Keep nesting shallow, use braces consistently, and consider compound conditions or early returns to flatten logic. Clear structure is as important as correctness.
Challenge: Ticket Pricing