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 →
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.
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 Routing Execution With if and else
Why does the second line under my if run even when the condition is false?
In what order should I write the conditions in an else if ladder?
What is the difference between if...else and two separate if statements with opposite conditions?
Why does my C++ if branch always run even though the condition looks false?
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 →