0

I'm trying to make a code where you input a number n and the code returns you the number in the Fibonacci sequence. Example: When inputting n = 1 the code returns 1, and when you input n = 2 the code returns 1, and when you input n = 3 the code returns 2, and so on. I'm quite a beginner with javascript so I don't know exactly how to do this.

<html>
<body>
    <script type="text/javascript">
    function fibonacci(){
    var a, b, n, result;
    a = 0;
    b = 1;
    for (var i = 0; i <= n; i++)
    {
        if(n == 1)
        {
            return 1;
        }
        if(n == 0)
        {
            return 0;
        }
        result = a + b;
        a = b;
        b = result;
        
    }
    document.getElementById("result").value = result;
    }
    </script>
    <form>
        <input id="n" type="number" placeholder="N">
        <input id="result" type="number" placeholder="Result" readonly="">
        
        <input id="calculate" type="button" value="Calculate" onclick="fibonacci()">
        <input type="reset" value="Clear">
    </form>
</body>
</html>
3
  • i <=n cannot happen if n is null no? Commented Feb 2, 2021 at 6:31
  • add this line n =document.getElementById("n").value Commented Feb 2, 2021 at 6:33
  • Where exactly ? Commented Feb 2, 2021 at 6:34

2 Answers 2

1

You didn't initialized n, right?

Add this line before for loop.

n =  document.getElementById("n").value

Check your browser console for errors, it shows this kind of errors correctly..

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

1 Comment

That works but my problem now is when I make n = 0 / n = 1 the code doesn't work. Also if I put n = 2 it should return 1 but it returns 2
0
  1. You should initialize n.
  2. Then remove n==0 and n==1 from for loop block.
  3. Update your code following,
<html>
<body>
    <script type="text/javascript">
    function fibonacci(){
    var n = document.getElementById("n").value;
    var result;
    var a = 0;
    var b = 1;
    if(n == 0 || n == 1)
    {
        result = n;
    }
    else{
      for (var i = 2; i <= n; i++)
      {
          result = a + b;
          a = b;
          b = result;

      }
    }
    document.getElementById("result").value = result;
    }
    </script>
    <form>
        <input id="n" type="number" placeholder="N">
        <input id="result" type="number" placeholder="Result" readonly="">
        
        <input id="calculate" type="button" value="Calculate" onclick="fibonacci()">
        <input type="reset" value="Clear">
    </form>
</body>
</html>

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.