• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Fibonacci Series using recursion gives stack overflow error

 
Ranch Hand
Posts: 106
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Saloon Keeper
Posts: 10705
86
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 106
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Carey Brown. Thanks a lot for your suggestion!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic