The else Statement
In the previous exercise we learned to use the if
statement. Often though, we need to execute some code even when the condition is not met. This is where the else
statement comes in.
Basic syntax:
if (condition) {
// code that executes when the condition is true
} else {
// code that executes when the condition is false
}
Usage examples:
int age = 15;
if (age >= 18) {
std::cout << "You can drive a car" << std::endl;
} else {
std::cout << "You cannot drive a car yet" << std::endl;
}
int points = 45;
if (points >= 50) {
std::cout << "Test passed" << std::endl;
} else {
std::cout << "Test failed" << std::endl;
}
/*
Prints:
You cannot drive a car yet
Test failed
*/
The else
statement ensures that one of the code blocks always executes:
- Either the code in the
if
block executes (when the condition is true) - Or the code in the
else
block executes (when the condition is false)
Instructions
Complete the condition so that it prints "Number is negative" if the if condition is not met.
Start programming for free
3/10