Recursive Functions in C#
factorial in C#

In this article, we are going to discuss recursion or recursive functions in C#. We will learn how to use recursive methods and what is the difference between recursive methods and regular methods.


What is Recursive Function?

Simply we can say recursive function is a function that calls itself, until it reaches at a specific condition. Each time a recursive function calls itself with new parameter value.

A famous example of recursion is factorial, factorial itself is the product of an integer and all the integers below it for example factorial four ( 4! ) is equal to 24.

1! = 1 = 1

2! = 2 x 1 = 2

3! = 3 x 2 x 1= 6

4! = 4 x 3 x 2 x 1 = 24

Computing Factorial in a Non Recursive Way

If you want to compute the factorial in a non recursive method, you would probably do something like this.

Computing Factorial in a Recursive Way

If you want to compute the factorial in a recursive method, which is shorter and smarter.

If we wanted to breakdown how the recursive method works, it would be something like this :

factorial of 4 breakdown

Advantages of Using Recursive Methods:

  • Recursive functions are usually much shorter and cleaners than iterative versions.
  • Reduce unnecessary calling of a function.
  • Many algorithms are defined recursively, so it is easy to implement them recursively.
  • Many data structures are naturally recursive (trees for example) and so it is natural to operate on them recursively.

Disadvantages of Using Recursive Methods:

  • Recursive functions are slightly slower than iterative ones.
  • They are very difficult to trace, debug and understand.
  • Can use a lot of stack space.
  • A recursive function uses more processor time.

Leave a Reply

Close Menu