Home Fibonacci Recursion Not working
Reply: 0

Fibonacci Recursion Not working

user1155
1#
user1155 Published in July 15, 2018, 9:20 pm

This question already has an answer here:

  • Java recursive Fibonacci sequence 34 answers

I probably made some stupid mistake, but whenever I try to run this program it always gives me a wrong answer. For example, I ask what is the 5th value of the Fibonacci sequence and it says 7.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

     // TODO add your handling code here:
    int n=0;
    try{
        n= Integer.parseInt(jTextField1.getText());    
    }
    catch(NumberFormatException e){
        jTextField2.setText("Please enter valid integers.");
    }
    jTextField2.setText("Fibo value is"+Fibonacci(n));
}  

private int Fibonacci(int n){

    System.out.println(n+"N");
    if (n <=1) {
        return n;
    }
    else{
        return Fibonacci(n-1)+(n-2);        
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.322279 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO