Multi-Tier Decision Chains: else-if and Nested Conditions

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

← Simple and Two-Way Decisions: if and if-elseNext lesson: The switch Statement →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
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

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.

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?
An else-if chain tests its conditions from the top, runs the block of the first test that is true, and skips all the rest. An optional final else handles the case where no test is true. C has no separate else-if keyword: each else if is simply an else whose single statement is another if. Because earlier tests already failed, later tests need not repeat them.
Why does the order of tests matter in an else-if chain?
Because the first true test wins, a loose test placed early can catch values meant for a later tier. If a chain checks score >= 300 before score >= 900, a score of 950 matches the first test and gets the lowest prize. The program compiles without warnings, so this logic error shows up only in testing. Put the strictest cut-off first, or give every test both ends of its range.
When should you use a nested if instead of an else-if chain?
A nested if fits when the second question only makes sense after the first answer, such as checking a token balance only for riders who are tall enough. Each level, however, pushes code to the right and adds one more condition to keep in mind. Beyond two or three levels, a flat chain with one message per test is usually clearer and gives the same answers.
What is a guard clause in a C program?
A guard clause is a test near the top that rejects impossible input and leaves at once, for example with return inside main. If valid scores run from 0 to 1000, a guard such as if (score < 0 || score > 1000) can print the rule and return. Without it, a value like -5 could fall through the chain to the lowest prize, a quiet wrong answer that is hard to notice.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) 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 Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 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 Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 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 Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →