EN VI

Javascript - Fibonacci numbers using while loop?

2024-03-17 22:00:06
How to Javascript - Fibonacci numbers using while loop

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);
}

Solution:

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);
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login