Matteo
Matteo

Reputation: 79

Fibonacci using `for` and `if`

Why does the below code return array = [] for n = 0? I would like it to return array = [0].

And for n = 1 it returns array = [0]? I would like it to return array = [0,1].

For n > 1 everything works fine.

let n = prompt("enter number")
let array = []
for (i = 0; i < n; i++){
    if (i < 2) {
        array.push(i);
    } else {
        let fib = (array[(i-2)] + array[i-1]);
        array.push(fib);
    }
}
console.log(array)

Upvotes: 0

Views: 66

Answers (1)

bub
bub

Reputation: 341

Your loop condition is i < n. If i = 0, then i is not less than n. Instead of checking that i < n, check that i <= n.

Fixed Code:

let n = prompt("enter number");
let array = [];
for (i = 0; i <= n; i++) { // FIXED HERE
    if (i < 2) {
        array.push(i);
    } else {
        let fib = array[i - 2] + array[i - 1];
        array.push(fib);
    }
}
console.log(array);

Upvotes: 2

Related Questions