Simple and Two-Way Decisions: if and if-else, Explained

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

← Logical Operators and Short-Circuit EvaluationNext lesson: Multi-Tier Decision Chains: else-if and Nested Conditions →

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

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.

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 Simple and Two-Way Decisions: if and if-else

How does an if statement work in C?
An if statement runs its block only when the test in parentheses is true, which in C means any non-zero value. If the test is zero, the block is skipped. Either way, the program continues after the closing brace. For example, if (tickets >= 50) prints a prize line only for 50 or more tickets, while a line after the brace prints every time.
What is the difference between if and if-else in C?
A plain if either runs its block or skips it, while if-else always runs exactly one of its two blocks, never both and never neither. For a game that costs 4 tokens, if (tokens >= 4) can start the game and subtract 4, and the else block can print that more tokens are needed. Code placed after both blocks runs in either case.
Why should you always use braces with an if statement in C?
Without braces, an if controls only the very next statement, no matter how the following lines are indented. Two indented printf lines under a brace-less if look guarded, but the second one runs every time, because the compiler reads statements, not indentation. Writing braces even for a single line makes the code do what it looks like, and clang's -Wmisleading-indentation flag warns about the brace-less version.
What happens if you put a semicolon after an if condition in C?
The semicolon becomes the entire body of the if, because a lone semicolon is an empty statement that does nothing. After if (tokens >= 4); the test controls nothing, and the block underneath is no longer attached to the if, so it always runs. Clang warns that the if statement has an empty body. Removing the semicolon fixes the bug.

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 →