DEV Community

Discussion on: Reasons To Use Recursion and How It Works

Collapse
 
joaomcteixeira profile image
João M.C. Teixeira

Nice post. Very interesting example with hello world being printed before the i value. It almost looks like a recursive decorator. ;-)

Recursion can be our best friend in many cases. But honestly, I am not sure that is best using recursion when iteration would work. I've run into some examples where recursion is needed and others where iteration is just best. What do you think?

I wrote once about Fibonacci with iteration and flat a list with recursion. Let me know your thoughts on it.

cheers

Collapse
 
manarabdelkarim profile image
Manar Imad

thank you .. I am glad you liked it 😊
and yes I agree with you 💯

looking at my example , the while function and the recursion function worked the same in result and time complexity .. but there is a difference that makes the while function better in this case which is the space complexity .
the while loop was updating the value of i which means the big O space complexity of the while function is O(1) "constant"
on the other hand, the recursion function was filling the stack every time with new function and different parameter , which means the big O space complexity is O(n)

so yes .. in many causes , using a normal iteration would be the best.

about your line in the article "I started this post to discuss that the Fib series might not be a good example to explain recursion." yes I totally agree and that's why I didn't use it
as you said there are better ways that will take less time and space

I liked your article I am gonna refer to it in my post

Collapse
 
joaomcteixeira profile image
João M.C. Teixeira

Thanks for the highlight 👏
and thanks for your comments. it is good to discuss. stay tuned. more is always coming 😉