Fibonacci sequence code. something little wrong somewhere but not sure how to fix it.

edited October 2016 in Questions about Code

So I need to write a code for a user to enter a number equal or greater than 3. Then the output should be the fibonacci sequence up until that number entered. For example, if a user enters 9, then the output should be 1,1,2,3,5,8. My problem is that it's showing a few extra terms and anything I try messes it up more. please help I would very much appreciate it. I'm very new to processing. Here's the code I have so far:

import javax.swing.JOptionPane;

Answers

  • edited October 2016
    import javax.swing.JOptionPane;
    
    int n;
    String number;
    int counter=0;
    
    
    int f0 = 0;
    int f1 = 1;
    int f2 = 1;
    
    int nextFib()
    {
    int result = f2;
    f0 = f1;
    f1 = f2;
    f2 = f0 + f1;
    return result;
    }
    void setup() {
    do {
    number= JOptionPane.showInputDialog("Enter an integer greater than or equal to three");
    n=Integer.parseInt(number);
    } while (n<3);
    
    
    
    
    print("1, ");
    for (int sum = 0; sum <n; sum++)
    {
    print(+nextFib()+", ");
    }
    }
    
  • Answer ✓

    You want to show Fibonacci numbers up until the number entered.

    But this isn't the check that your code is doing.

    If you input N, it's not giving you the Fibonacci numbers less than N.

    Instead, it's giving you the first N+1 Fibonacci numbers.

    You should rewrite your loop as a while loop, not a for loop.

    Your while loop should run until the number that it would print next is more than the limit entered.

  • figured it out thanks to your advice. Thanks so much! I just changed the for and didnt even actually need sum.

This discussion has been closed.