Recursion

=Recursion=

A recursive function is basically a function that calls itself. An easy example of recursion is when two mirrors are set parallel to each other and the nested images are a form of infinite recursion. When we implement our recursive functions we will avoid this type of infinite loop. Recursion can be incredibly useful to make very complicated code or repetitious code much shorter. It can be used to output the Fibonacci sequence, factorials, iterating through linked lists, and even solving the Tower of Hanoi.

Basic Fibonacci function: code format="cpp" int fib(int n){ if(n == 0) return 0; //stoppers else if(n == 1) return 1; else return fib(n-1)+fib(n-2); //calls itself } code

Basic Factorial function: code format="cpp" int factorial(int x){ if(x <= 1) return 1; //stopper else return x*factorial(x-1); //call } code

The returns labeled as stoppers are to prevent the function from calling itself infinitely.

=See Also=


 * Method