Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use recursion? [duplicate]

I am wondering, why do people use recursion? In most of my learning experience, I've found it to be much more inefficient that iterative methods, so why do people use it? Is it because you can simply write a shorter method? Is it used in real-world programming outside the classroom setting (or learning purposes)? If it is, please provide a good example if you can, I'm very curious.

Thanks in advance for your help! I really appreciate it!

like image 996
Billy Thorton Avatar asked Jul 29 '26 21:07

Billy Thorton


1 Answers

If you have a tree data structure and you want to walk over it in depth-first order, recursion is the only way to do it.

If you want to write a parser for a typical language having context-free rules, like every programming language in existence, a recursive-descent parser is a simple and natural way to do it. There is no iterative way to do it with limited storage.

like image 134
Mike Dunlavey Avatar answered Aug 01 '26 15:08

Mike Dunlavey