Tutorial by Examples

Recursion is when a method calls itself. Preferably it will do so until a specific condition is met and then it will exit the method normally, returning to the point from which the method was called. If not, a stack overflow exception might occur due to too many recursive calls. /// <summary>...
Recursion can be defined as: A method that calls itself until a specific condition is met. An excellent and simple example of recursion is a method that will get the factorial of a given number: public int Factorial(int number) { return number == 0 ? 1 : n * Factorial(number - 1); } ...
One of the uses of recursion is to navigate through a hierarchical data structure, like a file system directory tree, without knowing how many levels the tree has or the number of objects on each level. In this example, you will see how to use recursion on a directory tree to find all sub-directorie...
You can calculate a number in the Fibonacci sequence using recursion. Following the math theory of F(n) = F(n-2) + F(n-1), for any i > 0, // Returns the i'th Fibonacci number public int fib(int i) { if(i <= 2) { // Base case of the recursive function. // i is either 1...
The factorial of a number (denoted with !, as for instance 9!) is the multiplication of that number with the factorial of one lower. So, for instance, 9! = 9 x 8! = 9 x 8 x 7! = 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1. So in code that becomes, using recursion: long Factorial(long x) { if (x < 1...
Calculating the power of a given number can be done recursively as well. Given a base number n and exponent e, we need to make sure to split the problem in chunks by decreasing the exponent e. Theoretical Example: 2² = 2x2 2³ = 2x2x2 or, 2³ = 2² x 2In there lies the secret of our recursive al...

Page 1 of 1