UPI Study › Courses › C++ Programming › Free lessons › Lesson 4.6 Free with a free account
Deeply Nested Conditions
C++ Programming · Chapter 4: Decision MakingSection 4.6 · lesson 26 of 84video coming soon
← The Switch-Case MechanismNext lesson: Real-World Decision Scenarios →
In this lesson
Combining layers of logic, and removing the layers that don't earn their place.
- Write and indent nested if statements correctly
- Trace nested logic with a decision table
- Use the conditional operator where it clarifies
- Flatten depth with guards, stages and combined conditions
Transcript
Everything said in the video, section by section (1,250 words). Read along, or search it.
Opening Problem
Ticket Pricing Hides Three Levels
Real rules rarely arrive as one question. They arrive as a question inside a question inside a question. Take ticket pricing. The base price depends on the age band. A discount applies on Tuesdays. And members get a further reduction. Written as three questions, each inside the last, that's three levels deep before anything has been calculated. Three age bands, times Tuesday or not, times member or not: twelve endings, every one written out separately. The rules are simple. Only the shape of the code is complicated.
Core Idea
An If Inside Another If
An if can contain anything a statement can, including another if. The inner decision is reached only when the outer condition was true. That is exactly what, only relevant if, means in a rule. Here, if the age is under 13, the inner question asks whether they're a member: 108 or 120. Otherwise, the price is 200. Age 8, and a member, so 108. Two habits keep this readable. Always write the braces. And let the indentation tell the truth, one level per depth. It means nothing to the compiler and everything to the reader.
Common Mistake
Else Pairs With Nearest If
Here's why braces matter so much in nesting. Without them, an else attaches to the nearest if that doesn't already have one, however the lines are indented. In this fragment, the else is indented to pair with the age test. But it actually pairs with the member test. So a customer aged 40 gets no price at all, rather than the 200 the layout seems to promise. Braces remove the ambiguity permanently.
Combining Constructs
Mixing Switch and If
If and switch combine in both directions. A case body is a sequence of statements, so it can contain conditions. And a switch is an ordinary statement, so it can sit inside a branch. Here, case C opens its own braces, because it declares a variable, base. Inside, if the customer is a member, the base is reduced by 10 percent. Both directions are legal, and both cost the reader depth. So keep one only if it says something the flat version couldn't.
Code Walkthrough
Twelve Endings in Nested Form
Here's the ticket logic as it first comes out: every question inside the last one, with twelve separate endings, each price a literal. If the age is at least 0, then if under 13, then if Tuesday, then if member. And the same shape again, for adults, and for seniors. It works. It's also nearly impossible to change safely.
Quick Check
Pricing a Tuesday Senior
Pause and predict. A 70-year-old non-member comes in on a Tuesday. Which price does the code print? One hundred. Not under thirteen, not under sixty, so the senior branch; Tuesday, then not a member.
Tracing Method
Enumerating Combinations in a Table
Reading nested conditions to decide what they do is unreliable, because the eye follows the indentation, not the braces. The dependable method is to enumerate the combinations, and work out each result by hand. Then run them. An eight-year-old on an ordinary day pays 120. On a Tuesday, 80. As a member on a Tuesday, 72. An adult pays 200, or 144 as a member on a Tuesday. A 67-year-old member pays 126. The boundary row forces a decision. Is 12 still a child? The invalid row, an age of minus 3, checks input nobody should send. Here, the outermost test catches it.
The Cost
Routes Multiply and Rules Repeat
Each level of nesting multiplies the routes through the code. A reader trying to be sure about one line, must hold every condition above it in mind. One level gives 2 routes. Two give 4, three give 8, four give 16, and five give 32. Three levels is a common working limit. Not a law, but a good place to start asking why. There's a second cost that matters more in practice. In a deep structure the same rule is often written out once per path. The Tuesday discount here appears six times. Changing it from 40 to 50 means getting six literals right, and it's entirely ordinary to update three of the six.
Refactoring
Guards and Staged Computation
Three techniques dismantle it. First, a guard clause. The outermost if exists only to reject bad input, yet it wrapped the entire body. Invert it. Test for the bad case, handle it, and exit immediately. Everything after runs only in the normal case, with no extra indentation. Second, compute in stages, instead of branching to endings. Start the price at 200, the adult default. Then set 120 for children, or 140 for seniors. Then subtract 40 on Tuesdays, and apply 10 percent off for members. The rules stop being nested, because they never really were. They were independent adjustments to one number. Run the same eight inputs, and every answer matches the deeply nested version. Same answers, with far less nesting.
Third Technique
Joining Conditions With AND
Third, combine conditions that always travel together. If member, then if the age is at least 60, with no else anywhere, is really one condition. Join them with AND. Same behavior, one level less. The output is identical, and the code reads in one pass.
Results
What Flattening Bought Us
Here's what the three techniques bought. Maximum depth went from 4 to 1, so every line can be understood with one condition in mind. Endings went from 12 to 1. The Tuesday discount went from 6 appearances to 1, so changing it is a one-line edit that can't be half done. And the rules are now visible as rules, in the same order as the pricing policy. One more tip. Compound conditions help until they become a sentence. A test joining four conditions is flat, and still unreadable. Give it a name, like qualifies for loyalty rate, and test the name.
Extra Tool
Conditional Operator for Two Values
One more tool shortens a decision between two values. When a decision chooses between values rather than actions, the conditional operator says so in one line. It's written as the condition, a question mark, the value if true, a colon, and the value if false. Unlike if, it's an expression, so it produces a value wherever one is expected. Fee, initialized with is member, question mark, 120, colon, 150, does in one line what the if version needed two for. The variable has its value from the moment it exists. It's good for one choice between two values, or a choice inside a larger expression, like item or items. Avoid it for two actions, which is what if is for. And avoid chaining it. Chained conditionals are a reliable source of misreadings.
Caveat
When Depth Genuinely Belongs
Flattening isn't automatically right. There are three situations where depth genuinely belongs. When the inner question is meaningless unless the outer one holds. Asking whether a member's card has expired makes no sense for a non-member. When flattening would duplicate the outer test. Four combined conditions would hold four copies of one idea. And when each level has its own else. Two levels handling their own false cases do two jobs, and merging them with AND loses one response. So the working rule is a question, not a limit. At every level, ask what it's for. A guard against the invalid becomes a guard. A mere path to the inner test gets merged. A real dependency with its own alternative stays.
Key Takeaways
Brace, Trace, and Flatten Wisely
To summarize. Always brace nested conditions. An else pairs with the nearest unmatched if, whatever the indentation says. Trace nested logic with a table of every combination, including boundaries and invalid input. Use the conditional operator to choose between two values, not two actions. And flatten depth that isn't a real dependency, with guards, stages, and combined conditions. Here's something to think about. Deep code tends to write the same rule out on several paths. Why is that worse than the extra indentation?
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Deeply Nested Conditions
How does else pair with if in nested if statements in C++?
How do I trace nested if logic with a decision table?
How do I flatten deeply nested if statements in C++?
When should I use the conditional operator instead of an if statement?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →