A recursive method is nothing but a method which calls itself. Recursive methods are widely used in advanced programming and also in developing compilers. Recursive methods can also call other methods within it.
In this article we discuss about recursive method with couple of examples. Open Microsoft Visual Studio 2013 => Create simple Console Application => Add below code for Factorial number.
private long Factorial(int iFact)
{
if (iFact == 0)
return 1;
return iFact * Factorial(iFact - 1);
}
As shown above Factorial method is called within the Factorial method get the factorial of given number that means Factorial is the recursive method here. If we didn’t use the Factorial method recursively we have to write code as shown below to find the factorial number.
private long Factorial(int iFact)
{
if (iFact == 0)
return 1;
long value = 1;
for (int i = iFact; i > 0; i--)
{
value *= i;
}
return value;
}
As shown above this Factorial method taking more code as compared with the recursive Factorial method. By using recursive method we reduced the number lines of code.
Let’s discuss about one more example Fibonacci series for recursive method as shown below.
private long Fibonacci(int iFib)
{
if (iFib == 0 || iFib == 1)
return iFib;
return Fib(iFib - 2) + Fib(iFib - 1);
}
As shown above we created the Fibonacci() method as recursive to generate the Fibonacci series.