Commit f703e8b7 authored by Chris's avatar Chris
Browse files

[control-flow] finished section

parent 78e14ff2
Loading
Loading
Loading
Loading
+62 −2
Original line number Diff line number Diff line
@@ -12,7 +12,67 @@ fn main() {

    println!("{x}, {y}");

    // here's how to do a loop
    // loop {
    //     println!("again!");
    // }

    let mut counter = 0;
    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter + 2; // result == 10 + 2 == 12
        }
    };

    println!("The result of counter is {result}"); // and 12 will print here

    println!("labeled loop \'counting_up");
    let mut count = 0;
    'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
        println!("again!");
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                break 'counting_up;
            }
            remaining -= 1;
        }

        count += 1;
    }
    println!("End count = {count}");

    println!("while loop");
    let mut number = 3;
    while number != 0 {
        println!("{number}");
        number -= 1;
    }
    println!("LIFTOFF!!");

    println!("looping through a collection with \"for\"");
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("a[{index}] is {}", a[index]);
        index += 1;
    }
    // can also do
    for element in a {
        println!("the value is: {element}");
    }

    println!("here is a better liftoff implementation");
    for number in (1..4).rev() {
        println!("{number}!");
    }
    println!("LIFTOFF!!!");
}