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 :

  1. /* Description: find a factorial number using recursion */
  2. using System;
  3. namespace DemoProgramming
  4. {
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. int number;
  10. long fact;
  11. Console.Write("Enter a number: ");
  12. number = Convert.ToInt32(Console.ReadLine());
  13. fact = GetFactorial(number);
  14. Console.WriteLine("{0} factorial is: {1}", number, fact);
  15. Console.ReadKey();
  16. }
  17. private static long GetFactorial(int number)
  18. {
  19. if (number == 0)
  20. {
  21. return 1;
  22. }
  23. return number * GetFactorial(number - 1);
  24. }
  25. }
  26. }

Output :

C Sharp Language find a factorial number using recursion

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 :

  1. /* Description: find a factorial number using recursion (Iteration) */
  2. using System;
  3. namespace DemoProgramming
  4. {
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. int number;
  10. long fact;
  11. Console.Write("Enter a number: ");
  12. number = Convert.ToInt32(Console.ReadLine());
  13. fact = GetFactorial(number);
  14. Console.WriteLine("{0} factorial is: {1}", number, fact);
  15. Console.ReadKey();
  16. }
  17. static long GetFactorial(int number)
  18. {
  19. long result = 1;
  20. for (int i = 1; i <= number; i++)
  21. {
  22. result = result * i;
  23. }
  24. return result;
  25. }
  26. }
  27. }

Output :

C Sharp Language find a factorial number using recursion (Iteration)

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.


Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes