Flash cards
Review the key moves
What is the main idea behind C++ Else?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ ( condition ) {Put the learning moves in the order that makes the concept easiest to apply.
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false .
Syntax
if ( condition ) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}In the example below, the program checks the value of time . If it is less than 18, it prints "Good day". Otherwise, it prints "Good evening":
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."Because time is 20, the condition time < 18 is false, so the code inside the else block runs and prints "Good evening.". If time was less than 18, the program would print "Good day." instead.
Using a Boolean Variable
You can also store the condition in a boolean variable and use it in the if...else statement. This can make the code easier to read.
Example
int time = 20;
bool isDay = time < 18;
if (isDay) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."Tip
A name like isDay makes it easy to understand what the condition means.