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

55

u/MagicalPizza21 Software Engineer May 22 '25

Merge sort and quick sort are also examples of this.

30

u/Adventurous_Art4009 May 22 '25

Those are great examples. Sort the left side, sort the right side, merge them. No need to keep track of a stack of things to do next, because it's taken care of automatically.

8

u/Maleficent_Memory831 May 22 '25

When I learned this, we used turtle graphics. So the program was to draw fractals (Sierpiński curves). And this made it possible to literally see the recursion.

4

u/_-TheTruth-_ May 23 '25

The call stack IS the "stack of things". Cool!

5

u/mysticreddit May 22 '25

My example of sorting algorithms

  • Bubble
  • Insertion
  • Selection
  • Quick

0

u/Gorzoid May 22 '25

Is this meant to be relevant somehow?

4

u/mysticreddit May 22 '25

It is a clear, concise example of using recursion that /u/OddChoirBoy mentioned, but for Quick Sort.

Did you not read the code and comments?