UPI Study › Courses › Programming in C › Free lessons › Lesson 4.4 Free with a free account
Simple and Two-Way Decisions: if and if-else
Programming in C · Chapter 4: Conditional Logic, Decision Structures, and Practical ApplicationsSection 4.4 · lesson 22 of 785 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: Multi-Tier Decision Chains: else-if and Nested Conditions →← Logical Operators and Short-Circuit EvaluationNext lesson: Multi-Tier Decision Chains: else-if and Nested Conditions →
In this lesson
Making a C program choose whether to run or skip code.
- Write an if statement that runs a block only when its test is non-zero
- Use if-else so exactly one of two blocks runs
- Explain why braces should surround every if block
- Identify the bug caused by a semicolon after an if test
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 (670 words). Read along, or search it.
Opening Idea
Programs That Respond to What Happens
So far, every program you've written ran its lines from top to bottom, no matter what. Real machines don't. The arcade's token slot starts the game only if enough tokens went in. Otherwise, it flashes: insert more. That fork in the road is called a decision. With it, a program stops being a recording, and starts responding to what happens.
The if Statement
A Gate With a Test
An if statement is a gate with a test on it. The test goes in parentheses. If the test is true, meaning not zero, the program runs the block: the lines inside the curly braces. If it's false, the block is skipped. Either way, the program carries on after the closing brace. Here's a prize sign as a program. Win fifty tickets or more, and you earn the plush dragon. Sam, the arcade's tester, types in the tickets he won. First, sixty-four. The test is true, so the dragon line runs, and then thanks for playing. Run it again with twenty. The test is false, so the block is skipped. Thanks for playing sits outside the braces, so it appears both times.
Quick Check
Exactly Fifty Tickets
Quick check. Sam runs the same program once more, and this time types exactly fifty. Which lines does it print? Pause and predict. Run it. It prints both. Fifty is greater than or equal to fifty, so the or-equal part counts, and the dragon line runs. That's why Sam tests forty-nine and fifty, not just easy values. The boundary is where mistakes hide.
if-else
Exactly One of Two Blocks Runs
Often there's something to do in both cases. Add the word else, and a second block. The program always runs exactly one of the two blocks. Never both, and never neither. A game costs four tokens. With ten in hand, the game starts, and four are used, leaving six. With three, the else block runs instead: not enough tokens. Nothing is spent. Tokens now comes after both blocks, so it prints in both runs. And a block can hold as many lines as you like.
Common Mistake
Missing Braces Hide a Bug
C allows a shortcut. When the block holds only one statement, you may leave out the braces. Then the if controls only the very next statement. That's dangerous, because your eye reads indentation, and the compiler doesn't. Here's what Sam found. Both printf lines are indented under the if, so both look guarded. And with two tokens, the game shouldn't start. Build and run. No warnings, and start the game is skipped. But have fun still prints. Only the first line belonged to the if. GCC's usual warnings catch this, but clang's wall and W extra stay silent. Add the misleading indentation flag, and clang explains: statement is not part of the previous if. The cure costs two keystrokes. Always write the braces, even for one line. Then what the eye sees is what C does.
Common Mistake
A Semicolon That Empties the if
One more trap. Don't end the if line with a semicolon. In C, a lone semicolon is a complete statement that does nothing. So this line means: if the test is true, do nothing. The block underneath has no if in front of it any more, so it always runs. With two tokens, the game starts anyway. Clang does catch this one: if statement has empty body. Braces every time, and no semicolon after the parenthesis, prevent both bugs.
Quick Check
An Unguarded Subtraction
Quick check, with a new program. A player holds three tokens, and the if has no braces, but two indented lines. What does the last line print? Pause and predict. Build and run it. It prints tokens now, minus one. Three isn't at least four, so the start line is skipped. But the subtraction isn't guarded. It always runs, so the player loses four tokens for a game that never started.
Key Takeaways
Simple and Two-Way Decisions in Review
To sum up. An if runs its block only when the test is true, meaning not zero. An if-else always runs exactly one of its two blocks. Write braces every time, and never put a semicolon after the test. And test with values right at the edge of the rule, the way Sam does.
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 Simple and Two-Way Decisions: if and if-else
How does an if statement work in C?
What is the difference between if and if-else in C?
Why should you always use braces with an if statement in C?
What happens if you put a semicolon after an if condition in C?
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 →