Recursion in plain English C# with Example



Recursion in plain English C# with Example

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); 
} 
In this method, we can see that the method will take an argument, number. 
Step by step: 
Given the example, executing Factorial(4) 
1. Is number (4) == 1? 
2. No? return 4 * Factorial(number-1) (3) 
3. Because the method is called once again, it now repeats the first step using Factorial(3) as the new 
argument. 
4. This continues until Factorial(1) is executed and number (1) == 1 returns 1. 
5. Overall, the calculation "builds up" 4 * 3 * 2 * 1 and finally returns 24. 
The key to understanding recursion is that the method calls a new instance of itself. After returning, the execution of 
the calling instance continues. 

0 Comment's

Comment Form