Nested Conditions
A block of code can contain any code, even another if statement. An if inside the block of another if is called a nested condition. It's useful when one question only makes sense after another. At the cinema, for example, we first check whether the visitor has a ticket, and only then how old they are:
bool has_ticket = true;
int age = 15;
if (has_ticket) {
if (age >= 18) {
printf("Enjoy the movie\n");
} else {
printf("Sorry, this movie is for adults only\n");
}
} else {
printf("Please buy a ticket first\n");
}This prints:
Sorry, this movie is for adults onlyThe inner if statement runs only when has_ticket is true. Each else belongs to the if whose block ends with the } right before it: the first one to if (age >= 18), the second one to if (has_ticket). The indentation shows this at a glance: the inner blocks are indented by 4 more spaces, 8 in total, and each else is indented as much as its if.
Nested conditions can often be rewritten with && and else if. With the same variables, this code does the same:
if (has_ticket && age >= 18) {
printf("Enjoy the movie\n");
} else if (has_ticket) {
printf("Sorry, this movie is for adults only\n");
} else {
printf("Please buy a ticket first\n");
}The program gets to else if (has_ticket) only when the first condition is false. With a ticket, that means the visitor is under 18. Neither way is wrong: pick the one that's easier to read.
When neither of the two if statements has an else, a single if with && is almost always clearer. These two conditions:
if (has_ticket) {
if (age >= 18) {
printf("Enjoy the movie\n");
}
}do the same as a single condition with one level of indentation less:
if (has_ticket && age >= 18) {
printf("Enjoy the movie\n");
}Instructions
- 1
To ride the roller coaster, you must be at least 10 years old and at least 140 cm tall. Inside the
ifblock, below itsprintf, add a nestedifstatement: ifheightis at least140, printEnjoy the ride!, otherwise printYou must be at least 140 cm tall. The program prints:Age: 12, height: 135 cm You are old enough You must be at least 140 cm tall - 2
Change
heightto150and run the program. Now both conditions are true, so the program printsYou are old enoughandEnjoy the ride!.