Ranajoy Saha

Ranch Hand

Posts: 105

2

posted 1 year ago

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.

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.

posted 1 year ago

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.

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.

posted 1 year ago

- 2

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 wrote:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.