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

4

u/Maleficent_Memory831 May 22 '25

Not just conceptually easier, but much easier to implement. The stack is there for free, and sometimes to do a non-recursive implementation you need to implement storage to hold state.

Now often recursion is the same as a loop, such as tail recursion, but it's still written as recursion in some languages because it's so simple (ie, Lisp).

Ie, merge sort:

  • split into two sets
  • sort each set recursively
  • merge the two sets

It's very easy to understand. But write this as a loop (which is what I saw first time merge sort was explained) and it's much more complex.