Deeply Nested Conditions, Explained with Code Examples

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 →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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++?
An else pairs with the nearest preceding if that does not already have an else, no matter how the lines are indented. Indentation means nothing to the compiler. An else that looks aligned with an outer age test may actually belong to an inner member test. Writing braces around every if body removes the ambiguity permanently.
How do I trace nested if logic with a decision table?
A decision table lists every combination of inputs, with the result you work out by hand for each row. Then you run the code and compare. Reading nested code by eye is unreliable because the eye follows indentation, not braces. Include boundary rows, such as whether 12 still counts as a child, and an invalid row, such as an age of -3.
How do I flatten deeply nested if statements in C++?
Flatten nested conditions with guard clauses, staged computation, and combined conditions. A guard tests for the bad case first and exits, so the normal path needs no extra indentation. Staged computation starts with a default value and applies independent adjustments in order, which stops a rule like a Tuesday discount from being written out on every path. Joining conditions with && removes one level of nesting.
When should I use the conditional operator instead of an if statement?
Use the conditional operator when a decision chooses between two values rather than two actions. It is written condition ? valueIfTrue : valueIfFalse, and it is an expression, so it produces a value. For example, int fee = isMember ? 120 : 150; gives fee its value from the moment it exists. Avoid it for actions, and avoid chaining it, since chained conditionals are easy to misread.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

C++ Programming
3 credits · NCCRS
Enroll →