Recursion is a method of solving problems based on the
divide and conquers mentality. The basic idea is that you take the original
problem and divide it into smaller (more easily solved) instances of itself,
solve those smaller instances (usually by using the same algorithm again) and
then reassemble them into the final solution. Whenever a function calls itself,
creating a loop, then that's recursion.
Let's solve factorial of number by using recursion. We know
that in factorial number value is multiple by its previous number so our problem
is divided in small part.
using System;
namespace FactorialExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a
number");
int number = Convert.ToInt32(Console.ReadLine());
long fact = GetFactorial(number);
Console.WriteLine("{0}
factorial is {1}", number, fact);
Console.ReadKey();
}
private static long GetFactorial(int number)
{
if (number == 0)
{
return 1;
}
return number * GetFactorial(number-1);
}
}
}