Join 36000+ teachers and students using TTIO.
In computer science, recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. Such problems can generally be solved by iteration, but this needs to identify and index the smaller instances at programming time. Recursion solves such recursive problems by using functions that call themselves from within their own code.
Examples given in VB.Net - use as pseudocode and convert into your language of choice.
Think of recursion like a magic superpower that allows you to solve problems easily!
The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.
"The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions."
— Niklaus Wirth, Algorithms + Data Structures = Programs, 1976
Most computer programming languages support recursion by allowing a function to call itself from within its own code.
In order to be successfully recursive a recursive function must obey 3 rules:
3 Rules of recursion
Why use recursion?
Recursion is useful in many problems where iteration would prove difficult or impossible.
Stacks and Unwinding
Unwinding is the process of returning from one stack from back down to the next, and so on until recursion is complete.