UPI Study › Courses › Programming in C › Free lessons › Lesson 4.5 Free with a free account
Multi-Tier Decision Chains: else-if and Nested Conditions
Programming in C · Chapter 4: Conditional Logic, Decision Structures, and Practical ApplicationsSection 4.5 · lesson 23 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: The switch Statement →← Simple and Two-Way Decisions: if and if-elseNext lesson: The switch Statement →
In this lesson
Choosing among many outcomes with else-if chains and nested ifs.
- Trace an else-if chain to find which block runs
- Order tests from strictest to loosest or bound each range on both ends
- Flatten deeply nested if statements into a single chain
- Use a guard with return to reject invalid input early
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (955 words). Read along, or search it.
Opening Problem
Four Prizes From One Score
The Starlight Arcade doesn't hand out just one prize. Depending on the score, you get a gold trophy, a silver medal, a bronze ribbon, or a sticker. One if and one else can only make two choices. So how do you make four? And what happens if you put the tests in the wrong order? Sam found out the hard way, when a player who scored nine fifty went home with a ribbon.
else-if Chain
The First True Test Wins
Think of a prize counter with a row of boxes, from the best prize to the worst. The clerk checks the biggest box first. If the player is good enough, the clerk stops there. If not, the clerk moves down to the next box, and never checks two boxes for one player. That's an else-if chain: an if, then as many else-if parts as you need, then an optional final else, for none of the above. In fact, C has no else-if keyword. It's an else whose one statement is another if. C runs the tests from the top. The first true test wins, its block runs, and all the rest are skipped. Sam types a score of six forty. The nine hundred test says no. The six hundred test says yes: silver medal. The two boxes below are never even looked at. Notice the second test doesn't say, and less than nine hundred. It doesn't need to. To reach that line, the first test already said no.
Logic Error
Easiest Test First Gives the Wrong Prize
Because the first true test wins, the order of the tests is part of the logic. Sam wrote his version starting with the easiest question. It reads naturally, it compiles with no warnings, and it's wrong. The player scored nine fifty. The first test, at least three hundred, says yes, and the chain stops. A gold-level score gets a bronze ribbon. The compiler can't know what you meant. This is a logic error, and only a test run with the right score finds it.
Two Fixes
Strictest First or Both Range Ends
There are two cures. The first you've seen already: order the tests from the strictest to the loosest. The second: make every test name both ends of its range, using AND. Then no test can reach into another test's territory. Here the bronze test is still written first. But with nine fifty it's false, because nine fifty is not less than six hundred. So it's gold. The price is longer tests, and more chances for a typo at the edges. Use it when the ranges don't line up in a neat order.
Quick Check
A Missing Equals Sign at Six Hundred
Quick check. This new chain is in the right order, but every test uses greater than, with no equals sign. The score is exactly six hundred. Which prize prints? Pause and predict. Build and run it. It prints bronze ribbon. Six hundred is not greater than six hundred, so the silver test says no. The next test, greater than three hundred, says yes. One missing equals sign moved a whole score into the wrong tier, with no warning. That's why Sam tests every cut-off and the value just below it: two ninety-nine and three hundred, five ninety-nine and six hundred, and so on.
Nested if
A Height Rule Then a Token Rule
An if can also sit inside another if. That's called nesting. It fits when the second question only makes sense after the first answer. The Comet Coaster has two rules. Riders must be at least forty-eight inches tall, and the ride costs five tokens. For a fifty-inch player holding three tokens, the outer test passes, the inner test fails, and it prints: you need five tokens. It works. But each level pushes the code to the right, and makes you hold one more question in your head. At three or four levels, even the author gets lost.
Flattening
One Straight Chain Instead of Nesting
So, more than two or three levels of braces? Flatten. Give each test its own message, in a straight chain. Too short comes first. Then, not enough tokens. Then the happy case goes in the final else. Same questions, same order, same answer: you need five tokens. The flat version just stops hiding the second question inside the first. A tip before you nest: sketch a small table on paper, with a column for each question and a row for each outcome.
Guard Clause
Rejecting Impossible Scores Early
The cleanest way to avoid deep nesting is to deal with the bad cases first, and get out. Inside main, return ends the program on the spot. A test at the top that rejects impossible input and returns is called a guard. Scores run from zero to a thousand. Type minus five, and the guard prints the rule and leaves. The prize chain never sees it. Without the guard, the chain would have called minus five a sticker. That's a quiet wrong answer, the hardest kind to notice.
Quick Check
A Score of Exactly One Thousand
Quick check. Same program with the guard, and this time Sam types exactly one thousand. What does it print? Pause and predict. Run it. It prints gold trophy. One thousand is not greater than one thousand, so the guard lets it through. Then the very first test, at least nine hundred, says yes. A score right on the edge is a legal score, and the guard agrees.
Wrap-Up
Testing Every Cut-Off and the Value Below
Back to the prize counter, and the nine fifty that won a ribbon. Priya swapped Sam's tests, biggest cut-off first. Then Sam tried nine hundred and eight ninety-nine, six hundred and five ninety-nine, three hundred and two ninety-nine. Always the edges. All six were right.
Key Takeaways
Chains and Nesting in Review
To sum up. An else-if chain runs its tests from the top, and the first true test wins. So put the strictest test first, or name both ends of every range. Flatten deep nesting into one straight chain, and let a guard reject bad input early. And test every cut-off, plus the value just below it.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. 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 All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C 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 Multi-Tier Decision Chains: else-if and Nested Conditions
How does an else-if chain work in C?
Why does the order of tests matter in an else-if chain?
When should you use a nested if instead of an else-if chain?
What is a guard clause in a C program?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →