0

I am trying to write a script that will create numbers in Fibonacci order, I don't understand why this is not working.

var output = [];
var n = output.length;
var nextNum = output[n-1] + output[n-2];

function fibo (numQuantity) {
for (var i=1; i<numQuantity ; i++)
{
  if (n>1){ 
  output.push(nextNum);
  console.log(output);
}
else if (n<2)
  {output.push(1);
  console.log(output);}
}
}
2
  • your n value never changes also your nextNum value never changes? Commented May 12, 2020 at 17:22
  • Youre not changing n anywhere. It remains 0 as assigned at var n = output.length; Commented May 12, 2020 at 17:22

3 Answers 3

1

In your original code your n never changes as you only assigned it on start.

    var output = [];


    function fibo (numQuantity) {
    for (var i=1; i<numQuantity ; i++)
    {
      var n = output.length;
      var nextNum = output[n-1] + output[n-2];
      if (n>1){ 
        output.push(nextNum);
        console.log(output);
      }
      else if (n<2)
      {
        output.push(1);
        console.log(output);
      }
    }
    }

    fibo(10)

In Javascript numbers are passed by value not reference so they are not the same object in memory. So when the array length changes your n value stays at 0 because they are not the same object.

Sign up to request clarification or add additional context in comments.

Comments

0

function fibo(numQuantity) {
  let output = [0, 1];
  
  if(numQuantity < 2) {
    return output.slice(0, numQuantity);
  }
  
  for(let i = 2; i < numQuantity ; i++) {
    const n = output.length
    output.push(output[n - 1] + output[n - 2])
  }
  
  return output;
}

console.log(fibo(1))
console.log(fibo(2))
console.log(fibo(3))
console.log(fibo(4))

Comments

0

Check this fiddle: https://jsfiddle.net/37a4burz/

You need to add n++ to end of your code and change end condition.

Here is full code:

var output = [];
var n = output.length;
var nextNum = output[n-1] + output[n-2];

function fibo (numQuantity) {
    for (var i=1; i<= numQuantity ; i++)
    {
        if (n==0) {
            output.push(0);
            console.log(output);
        }
        else if (n==1) { 
            output.push(1);
            console.log(output);
        }
        else if (n>1) {
            output.push(output[n-1] + output[n-2]);
            console.log(output);
        }

        n++;
    }
}

fibo(7);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.