'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)
Solution 1:[1]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
