Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading