Wednesday 1 May 2019

What is recursion? tccicomputercoaching.com

Recursion means function calls itself n times.

Factorial is Best Example of Recursion. How recursion works?



void recurse()
{
    ... .. ...
    recurse();
    ... .. ...
}

int main()
{
    ... .. ...
    recurse();
    ... .. ...
}

Example:

int factorial(int n)
{
If (n==1)
return 1;
else
return (n* factorial(n-1));
}

In above factorial example : factorial function calls itself by multiplying n with factorial of n-1 and stops when it reaches to the bas condition at fact 1 by returning 1.

So function calling done in the following way.

fact(5).

5*fact(4) //calls fact(4)

5*4*fact(3)

5*4*3*fact(2)

5*4*3*2*fact(1)

5*4*3*2*1*1 // stops here

Output:

120

To learn more about in detail Programming

Join us @ TCCI Computer Coaching

Call us @ 9825618292

Visit us @ www.tccicomputercoaching.com

No comments:

Post a Comment