Lesson contents

Choose with if and else

Check a condition to choose which step runs next.

Simple example

Start2 < 3
Result1
main.rs
fn main() {
    if 2 < 3 {
        println!("{}", 1);
    } else {
        println!("{}", 0);
    }
}
Output
1
Advertisements

Everyday examples

A family needs 4 seats. There are 3 left. Show 1 if everyone fits, or 0 if they need another bus.

Start4 → 3
Result0
main.rs
fn main() {
    let needed: i64 = 4;
    let free: i64 = 3;
    if needed <= free {
        println!("{}", 1);
    } else {
        println!("{}", 0);
    }
}
Output
0
Run the example
Terminal
rustc main.rs
./main
Official documentation