Nested If - Else
Part of the Fundamentals section of Coddy's C++ journey — lesson 32 of 74.
We can nest if-elif-else statements within each other. This allows us to create hierarchical decision-making structures.
For example:
if (age > 18) {
if (hasLicense) {
std::cout << "You can drive";
} else {
std::cout << "Get a license first";
}
} else {
std::cout << "Too young to drive";
}It can be infinitely nested:
if (condition1) {
if (condition2) {
if (condition3) {
// if condition1, condition2 and condition3 are true
}
}
}Challenge
BeginnerCreate a program that checks if someone can ride a rollercoaster. The requirements are:
- Must be at least 12 years old
- Must be taller than 150cm
- If they meet both requirements but are under 15, they need adult supervision
Print exactly these messages for each case:
- If too young:
Sorry, you are too young - If not tall enough:
Sorry, you are not tall enough - If under 15 and no adult:
Sorry, you need an adult with you - If under 15 with adult:
You can ride with adult supervision! - If 15 or older and tall enough:
You can ride by yourself!
Cheat sheet
You can nest if-elif-else statements within each other to create hierarchical decision-making structures:
if (age > 18) {
if (hasLicense) {
std::cout << "You can drive";
} else {
std::cout << "Get a license first";
}
} else {
std::cout << "Too young to drive";
}Nesting can be done infinitely:
if (condition1) {
if (condition2) {
if (condition3) {
// if condition1, condition2 and condition3 are true
}
}
}Try it yourself
#include <iostream>
int main() {
int age, height;
bool hasAdult;
std::cin >> age >> height >> hasAdult; // Don't change this line
// Write your code below
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else