Menu
Coddy logo textTech

Nested If - Else

Part of the Fundamentals section of Coddy's Rust journey — lesson 28 of 75.

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 {
        println!("You can drive");
    } else {
        println!("Get a license first");
    }
} else {
    println!("Too young to drive");
}

It can be infinite nested:

if condition1 {
	if condition2 {
		if condition3 {
		    // if condition1, condition2 and condition3 are true
		    ...
		}
	}
}
challenge icon

Challenge

Beginner

Create 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're too young
  • If not tall enough: Sorry, you're 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 {
        println!("You can drive");
    } else {
        println!("Get a license first");
    }
} else {
    println!("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

use std::io;

fn main() {
    let mut age_input = String::new();
    let mut height_input = String::new();
    let mut adult_input = String::new();
    
    io::stdin().read_line(&mut age_input).unwrap();
    io::stdin().read_line(&mut height_input).unwrap();
    io::stdin().read_line(&mut adult_input).unwrap();
    
    let age: i32 = age_input.trim().parse().unwrap();
    let height: i32 = height_input.trim().parse().unwrap();
    let has_adult: bool = adult_input.trim().parse().unwrap();

    // Write your code below
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals