r/computerscience • u/ShadowGuyinRealLife • 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
View all comments
Show parent comment
5
u/not-just-yeti May 22 '25
Flip-side: Recursion & structs lets you emulate (implement) a stack, and loops.
Mathematician's wacky view: the natural-numbers are recursively defined. So iteration & arrays are built on top of recursion [specifically: tail-recursion which can be implemented efficiently on hardware].
If you have recursion (and the ability to "pass code" i.e. pass functions), you can write
forandwhileas ordinary functions; you don't need them as built-in keywords that must be provided by the language.