Smartie
Smartie

Reputation: 107

Fibonacci code for loop not returning values

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>

Upvotes: 0

Views: 93

Answers (2)

Kawser Habib
Kawser Habib

Reputation: 1422

  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>

Upvotes: 0

Sameera K
Sameera K

Reputation: 1438

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..

Upvotes: 1

Related Questions