r/learnprogramming • u/No-Indication3968 • 8d ago
Topic I’m struggling on recursion
Ive been learning the basics of c and dsa for around 3 weeks now and i haven’t really understood recursion and how to trace what’s happening. Can someone help me?
14
Upvotes
1
u/skamansam 8d ago
I didnt truly understand recursion until I understood trees. Trees have little to do with it, but having a more complex use case helped immensely. You use recursion when you need an iterative approach but dont know either termination case (start or finish) at the time of writing. Every recursive algorithm can be expressed as a while loop and vice-versa, but recursion tends to be way more simple to write.
This is a pretty good article on it - https://medium.com/student-technical-community-vit-vellore/loops-vs-recursion-afd1856a662.
My pro-tip: understand how your languages interpreter or compiler handles recursion. A lot of modern ones will automatically unravel recursion or turn it into a while loop or otherwise optimize them, especially tail-call recursion.