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 only

The 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

To ride the roller coaster, you must be at least 10 years old and at least 140 cm tall. Inside the if block, below its printf, add a nested if statement: if height is at least 140, print Enjoy the ride!, otherwise print You 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

Change height to 150 and run the program. Now both conditions are true, so the program prints You are old enough and Enjoy the ride!.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

10/12