Routing Execution With if and else | C++ Programming

UPI Study › Courses › C++ Programming › Free lessons › Lesson 4.4 Free with a free account

Routing Execution With if and else

C++ Programming · Chapter 4: Decision MakingSection 4.4 · lesson 24 of 84video coming soon

← Mapping Decision Paths VisuallyNext lesson: The Switch-Case Mechanism →

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

In this lesson

The first construct that decides which lines run.

  • Write an if statement with and without braces
  • Choose between paths with if...else
  • Order an else if ladder correctly
  • Spot the errors that compile but misbehave

Transcript

Everything said in the video, section by section (1,153 words). Read along, or search it.

Opening Idea

Conditions Decide Which Lines Run

Everything so far has run in the order it was written, every time, without exception. The if statement is the first construct that changes that. It lets a condition decide which lines run at all. It's the point where a program stops being a fixed list of steps, and starts responding to its situation.

Definition

Anatomy of an If Statement

An if statement has two parts: a condition in parentheses, and a body that runs only when that condition is true. The condition is any expression producing true or false, so comparisons, and conditions layered with AND, OR and NOT, all plug straight in. Here, if the temperature is greater than 40, print a heat warning. At 45, it's true, so the body runs. Three details, because each produces an error message that doesn't obviously point at the cause. The parentheses are required. There's no semicolon after the closing parenthesis. And there's no then keyword. The body simply follows.

Braces

Indentation Does Not Group Statements

A pair of braces groups any number of statements into one block, which the if treats as a single unit. Without braces, an if controls exactly one statement, the very next one, and nothing beyond it. Here, both lines are indented under the if, so they look controlled. But only fee equals 50 is. The notice prints for every item, overdue or not. Indentation controls nothing: the compiler reads punctuation, and the human reads layout. Add braces, and the notice is inside the branch where it was plainly meant to be. So use braces every time, even for one statement. They cost two characters, and a line added later lands where it belongs.

Definition

Else Supplies the Alternative

Adding else supplies the alternative. If the score is at least 40, print pass. Otherwise, print fail. Exactly one of the two bodies runs. Never both, and never neither. Else carries no condition of its own. Its meaning is fixed: every case where the if condition was false.

Comparison

Else Versus Two Opposite Ifs

That's a stronger guarantee than two separate ifs with opposite conditions. Those must be kept opposite by hand. Say someone edits the first test to greater than 40, and forgets the second. A score of exactly 40 now matches neither. Both conditions are evaluated, and nothing is printed, with no error to tell you. With else, changing the condition updates both branches at once.

Worked Example

Following a Score Down the Ladder

When there are more than two outcomes, an else can be followed immediately by another if. Chaining these produces a ladder. Follow a score of 75 down it. At least 90 is false, so carry on. At least 80 is false, so carry on. At least 70 is true, so the grade is C, and the program leaves the ladder entirely. The rungs below are never even tested. The first true condition has its body run, and every remaining rung is skipped. Each rung only has to rule out what's left, so by the time the test for 80 is reached, everything of 90 and above has gone. No upper bound is needed.

Quick Check

Trace 95 Through Misordered Tests

Because the first true rung wins, order is load-bearing. Here are the same tests, ordered wrongly: at least 40 first, then 70, then 90. Quick check. What grade does a score of 95 get? Pause, and trace it.

Answer

Strictest Test Goes First

D. Ninety-five satisfies the first test, so the ladder stops right there. In fact, everyone who passes gets a D. The correct order puts the most demanding test first, so each rung excludes everything the rungs above already claimed. Now 95 gets its A. And keep a closing else, with no condition. Even when you believe the tests are exhaustive, it's the difference between handling a surprise, and silently doing nothing.

Common Mistake

The Dangling Else Problem

When an if sits inside another if and the braces are omitted, an else underneath becomes ambiguous to the eye. The language isn't ambiguous. An else attaches to the nearest preceding if that doesn't already have one. This is the dangling else. Here, the else is indented to line up with the outer if, is member. But it actually belongs to the inner one, balance greater than 0. So a member with no balance gets a message saying they're not a member. And a non-member falls through both branches, and nothing happens at all. Braces on every body make the attachment explicit, and the dangling else can't occur. That's the second bug the brace habit eliminates outright.

Common Mistake

Single Equals Instead of Double

Two more errors deserve their own attention, because neither is a spelling mistake. Each produces code the compiler accepts, that behaves nothing like it reads. The first: a single equals where double equals was meant. If status equals 1 assigns 1 to status, then uses that stored value as the condition. Any non-zero value counts as true, so the branch runs every time, and status has been quietly overwritten on the way past. Most compilers warn about this. So switch warnings on, and read them.

Common Mistake

The Stray Semicolon After Conditions

The second: a semicolon after the condition. A semicolon is a complete, empty statement, and an empty statement is a perfectly legal body. So the if controls nothing. The condition is tested and discarded, and the block below is just an ordinary block. The heat warning prints at 20 degrees. It's hard to see, because it's a single character at the end of a line that otherwise looks right.

Troubleshooting

Matching Symptoms to Causes

Here are symptoms, causes and fixes. Branch always runs, and a variable changed? A single equals written for double equals. Branch always runs, and nothing changed? A stray semicolon after the condition. There's never one there. Some branch lines always run? Braces are missing. An else acting on the wrong condition? A dangling else. Everything lands in one rung? The least demanding test came first. And an error about an else without a previous if? Check the brace pairing right above it.

Review Checklist

Four Questions for Any Decision

When you meet a decision you didn't write, four questions settle whether it's right. Ask the same four of your own. Is every case covered? Follow the rungs down, and ask what happens to a value none of them match. Can two cases both match? In a ladder that's harmless, but order is then carrying meaning, and that should be obvious. What happens exactly at each boundary? A score of exactly 40 belongs to one rung, and that's where off-by-ones live. And does the punctuation agree with the indentation? Braces on every body, no stray semicolons, every else visibly attached.

Key Takeaways

Summary and Count Equals Zero Puzzle

To summarize. An if runs its body only when its condition is true. Without braces, it controls exactly one statement, whatever the indentation says. Else chooses exactly one of two paths. A ladder tests from the top, and the first true rung wins, so the strictest test goes first. Three errors compile but misbehave: a single equals for double equals, a stray semicolon, and a dangling else. Braces prevent two of them. Here's something to think about. What does, if count equals 0, with a single equals sign, actually do? Does the body ever run? And what happens to count?

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 Routing Execution With if and else

Why does the second line under my if run even when the condition is false?
Without braces, an if controls exactly one statement, the very next one, no matter how the following lines are indented. The compiler reads punctuation, not layout. In if (fee == 50) cout << "Late"; followed by an indented second cout line, that second line prints for every item. Wrapping the body in braces puts both statements inside the branch, so braces on every body avoid this bug.
In what order should I write the conditions in an else if ladder?
Put the strictest test first, because the first true condition runs and the rest of the ladder is skipped. With tests of score >= 90, then score >= 80, then score >= 70, a score of 75 stops at the 70 rung. Each rung only rules out what remains, so no upper bound is needed. If score >= 40 comes first, a 95 gets a D. End with a plain else for unexpected values.
What is the difference between if...else and two separate if statements with opposite conditions?
An if...else guarantees that exactly one of its two bodies runs, while two separate ifs depend on you keeping their conditions opposite. Suppose you test score >= 40 for pass and score < 40 for fail, then change the first to score > 40. A score of exactly 40 now matches neither, so nothing prints and no error appears. Else has no condition of its own, so editing the if condition updates both branches.
Why does my C++ if branch always run even though the condition looks false?
Two common causes are a single equals sign and a stray semicolon, and both compile. In if (count = 0), the code assigns 0 to count and then tests that value; since 0 is false, the body never runs, but count is overwritten. A non-zero assignment makes the branch run every time. A semicolon right after the closing parenthesis gives the if an empty body, so the block below always runs.

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 →