CodeBlanks Logo Icon CodeBlanks

Loop and exit

Keep calculating with loop, break and a quit command.

Loop and exit

The calculator must keep running until the user types çık. loop is an infinite loop left with break. On every iteration the buffer is cleared with clear:

let mut girdi = String::new();
loop {
    girdi.clear();
    if io::stdin().read_line(&mut girdi).unwrap() == 0 {
        break;              // EOF (Ctrl+D)
    }
    let satir = girdi.trim();
    if satir == "çık" {
        break;
    }
    match isle(satir) { /* ... */ }
}

loop is an expression

break can also return a value, so loop can be used as an expression:

let mut n = 1;
let ilk_buyuk = loop {
    n *= 3;
    if n > 100 {
        break n;
    }
};
println!("{ilk_buyuk}");  // 243

continue skips the rest of the iteration; for example, to skip empty lines.

Practice Command loop

Try the loop with an array instead of stdin: process the commands ["5 + 1", "", "çık", "9 * 9"] in order; continue on an empty line, break on "çık", otherwise print the line as işlendi: .... Print güle güle at the end.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    for komut in ["5 + 1", "", "çık", "9 * 9"] {
        if komut.is_empty() {
            continue;
        }
        if komut == "çık" {
            break;
        }
        println!("işlendi: {komut}");
    }
    println!("güle güle");
}

Expected output

işlendi: 5 + 1
güle güle

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if <code>girdi.clear()</code> isn't called in the loop?

  • No input is read
  • The new line is appended to the old one and parsing breaks Correct answer
  • Nothing
  • The program crashes

Explanation: read_line appends to the existing String; without clearing it accumulates like "12 * 3\n5 + 1\n".

2 Leave the loop

Question
if satir == "çık" {
    ____;
}
Answer
if satir == "çık" {
    break;
}

Explanation: break ends the nearest loop.

3 Statement and effect

Term Meaning
loop Infinite loop
break Ends the loop
break n Returns a value
continue Moves to the next iteration

All lessons in Beginner