 # C# Recursion :

### What Is Recursion?

We call an object recursive if it contains itself, or if it is defined by itself. Recursion is a programming technique in which a method makes a call to itself to solve a particular problem. Such methods are called recursive.

#### Example :

 ``` /* Description: find a factorial number using recursion */ using System; namespace DemoProgramming { class Program { static void Main() { int number; long fact; Console.Write("Enter a number: "); number = Convert.ToInt32(Console.ReadLine()); 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); } } } ```

#### Output : ### Recursion or Iteration :

The calculation of factorial is often given as an example when explaining the concept of recursion, but in this case, as in many others, recursion is not the best approach. Very often, if we are given a recurrent definition of the problem, the recurrent solution is intuitive and not posing any difficulty, while iterative (consecutive) solution is not always obvious.

In this particular case the implementation of the iterative solution is as short and simple, but is a bit more efficient:

#### Example :

 ``` /* Description: find a factorial number using recursion (Iteration) */ using System; namespace DemoProgramming { class Program { static void Main() { int number; long fact; Console.Write("Enter a number: "); number = Convert.ToInt32(Console.ReadLine()); fact = GetFactorial(number); Console.WriteLine("{0} factorial is: {1}", number, fact); Console.ReadKey(); } static long GetFactorial(int number) { long result = 1; for (int i = 1; i <= number; i++) { result = result * i; } return result; } } } ```

#### Output : ### Which is Better : Recursion or Iteration?

If the algorithm solving of the problem is recursive, the implementation of recursive solution can be much more readable and elegant than iterative solution to the same problem.

Note : Recursion is powerful programming technique, but we have to think carefully before using it. If used incorrectly, it can lead to inefficient and tough to understand and maintain solutions.