Fibonacci numbers using while loop

43 Views Asked by At

Here my while condition is working, even if the value of c is greater than user Input, Am I missing anything?

function fibonacciSequence() {
var a = 0;
var b = 1;
var userInput = parseInt(prompt("Enter the number for a Fibonacci Sequence: "));
var c = a + b;
var fibonacciArray = new Array();
fibonacciArray.push(a);
fibonacciArray.push(b);
while (c\<userInput) {
c = a + b;
a = b;
b = c;
fibonacciArray.push(c);
} c = a + b;
alert(fibonacciArray);
}
1

There are 1 best solutions below

3
ADITYA On BEST ANSWER

We need to ensure that c is calculated before the comparison is made.

function fibonacciSequence() {
    var a = 0;
    var b = 1;
    var userInput = parseInt(prompt("Enter the number for a Fibonacci Sequence: "));
    var c;
    var fibonacciArray = [a, b]; // Initialize array directly

    while ((c = a + b) <= userInput) {
        a = b;
        b = c;
        fibonacciArray.push(c);
    }

    alert(fibonacciArray);
}