Conditionals & Logic
Learn how to use conditionals and logic to build programs that generate different outcomes.
StartKey Concepts
Review core concepts you need to learn to master this subject
if
Statement
if
Statement
if (a == 10) {
// Code goes here
}
An if
statement is used to test an expression for truth.
- If the condition evaluates to
true
, then the code within the block is executed; otherwise, it will be skipped.
Conditionals & Logic
Lesson 1 of 2
- 1Every program we’ve seen so far has only had one possible path of execution — they all execute line by line, from top to bottom. And every time you run one of those programs, it gives you the same …
- 2Before we dive deep into the syntax of the if statement, let’s do a demo! Here, we have coinflip.cpp program that simulates a coin toss: - 50% of the time, it’s Heads. - 50% of the time, i…
- 3An if statement is used to test an expression for truth and execute some code based on it. Here’s a simple form of the if statement: if (condition) { some code } If the condition is true, …
- 4When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called relational operators. To have a condition, we need relati…
- 5We can also add an else clause to an if statement to provide code that will only be executed if the condition is false. Here’s a form of an if statement that includes an else clause: if (condition…
- 7Now that we know how if, else if, else work, we can write programs that have multiple outcomes. Programs with multiple outcomes are so common that C++ provides a special statement for it… the swi…
What you'll create
Portfolio projects that showcase your new skills
Magic 8-Ball
We've learned a powerful tool in C++ — control flow! It's so powerful, in fact, that it can be used to tell someone's fortune.
Harry Potter Sorting Hat Quiz
Write a program that asks the user some questions and places them into one of the four Houses!
Rock, Paper, Scissors, Lizard, Spock
The Big Bang Theory Edition!
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory