Recursion

Recursion:

Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem.
In programming terms, the process of function calling itself is called recursion. Of course, it must be possible for the recursive function to sometimes be completed without the recursive call.

For example, recursion can be used to calculate the factorial of a number. The factorial of a number x is written x! and is calculated as follows:

x! = x * (x-1) * (x-2) * (x-3) * … * (2) * 1

However, you can also calculate x! like this:

x! = x * (x-1)!

Going one step further, you can calculate (x-1)! using the same procedure:

(x-1)! = (x-1) * (x-2)!

You can continue calculating recursively until you’re down to a value of 1, in which case you’re finished.

Eg:
fact(5) = 5 * fact(4)
fact(5) = 5 * 4 * fact(3)
fact(5) = 5 * 4 * 3 * fact(2)
fact(5) = 5 * 4 * 3 * 2 * fact(1)
fact(5) = 5 * 4 * 3 * 2 * 1
fact(5) = 5 * 4 * 3 * 2
fact(5) = 5 * 4 * 6
fact(5) = 5 * 24
fact(5) = 120

null

Mr. Sandeep Soni

Founder, Trainer & CEO, Deccansoft Software Services.

Sandeep has 21 yrs of experience working in various Microsoft Technologies/Platforms incl. VB6.0, ASP, VC++, VB.NET, C#. He is involved in managing and architecting projects at Deccansoft. He will be your liaison to Deccansoft, for any kind of communication and project updates. He knows what works and what doesn’t, and what practices are most suitable for design and programming with the ultimate goal of producing a quality system.