r/computerscience • • May 22 '25

Discussion Why Are Recursive Functions Used?

Why are recursive functions sometimes used? If you want to do something multiple times, wouldn't a "while" loop in C and it's equivalent in other languages be enough? I am not talking about nested data structures like linked lists where each node has data and a pointed to another node, but a function which calls itself.

106 Upvotes

152 comments sorted by

View all comments

Show parent comment

1

u/ArtisticFox8 May 22 '25

Not all recursion functions are as simple though. I think sometimes you need the whole recursion tree (for example 0/1 knapsack)

This is equivalent to 1D DP, whereas sometimes you need branching (and a for example binary recursion tree appears)

2

u/AdamWayne04 May 22 '25

Of course, which is why I linked Ackermann's function below (besides the fact that formatting is sometimes useless in the mobile app)

1

u/ArtisticFox8 May 22 '25

Nice, thanks!

Could you do something which otherwise makes a binary recursion tree without a call stack? Like the 0/1 Knapsack I mentioned. Im curious if there is some clever trick.

Or, pushing it even further, parsing an infix expression (I did it with an AST with recursion with the call stack)