Why is my Fibonacci program overshooting?

Hi, my code is generate Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, ...).
When i put a condition (n > b), for example - 30. My code exceeds this condition. Why so? Explain, please.

fn main() {
    fibonacci(30);
}

fn fibonacci(n: u32) {
    let mut a = 0;
    let mut b = 1;

    println!("{}\n{}", a, b);

    while n > b {
        a += b;
        println!("{}", a);
        b += a;
        println!("{}", b);
    }
}

P.S. Also, I will not give up advice on the code :slightly_smiling_face:

I gave it a quick try on the playground, and it seems to be working exactly as you specified it:

0
1
1
2
3
5
8
13
21
34

The reason it prints the 34 is because of iteration.
In the almost-last iteration, it prints "b = 21".
Then it checks: n > b (32 > 21), which is still true.
Then it increments (getting 34!) and prints, before checking again.

In general: the while loop checks its condition before execution of each loop.
Many other languages also provide a "do-while" loop, that checks after the first iteration (and after each subsequent loop).
Rust doesn't have a do-while, although you can hack one together using loop+break, or black magic

3 Likes