Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Fibonacci Series using recursion gives stack overflow error  RSS feed

 
Ranajoy Saha
Ranch Hand
Posts: 105
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Everyone

I have started with recursion programming lately. Solved two classic recursion problems on adding numbers within a given range sum(int m, int n), and factorial of a number using recursion. I tried my hand at printing fibonacci series using recursion but then thios happened. "Exception in thread "main" java.lang.StackOverflowError". This is my code using recursion.



And this is the code without recursion where I check whether a particular number lies in the Fibonacci Series



I am not able to dry run my own program on recursion. If someone could help me out.
 
Paul Clapham
Sheriff
Posts: 22472
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do recursion, as in your fibonacciSeries method, you should have some value which gets reduced to zero (or some similar target). That's so you don't have an infinite number of recursions.

But you don't have that. I'm sure you thought that your code did have a value which gets reduced on every iteration, but it actually doesn't.
 
Carey Brown
Bartender
Posts: 2980
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ranajoy Saha wrote:
Your problem is on line 13. You use terms--, which is post decrement, but passes the value BEFORE the decrement takes place. Just use terms-1.
 
Ranajoy Saha
Ranch Hand
Posts: 105
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Carey Brown. Thanks a lot for your suggestion!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!