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. What usually goes wrong. What you see What caused it How to fix it --- --- --- An 8-year-old member prints MEMBER The membership test ran before the age test Decide age first, and ask about membership only inside the branch for 13 and
Challenge: Ticket Pricing