Recursion:
The programming language allows you to divide your program into the
functions. Using functions, your program becomes easier to understand and to
debug. Also the functions can be shared among various programs. We can call a
function inside a function, it is known as nesting of functions. The
programming language C even allows calling a function itself. When a function
calls itself then it is known as recursive function. The process of a function
calling itself is known as Recursion. Here is the example to calculate
the factorial of a number:
int factorial(int a)
{
if (a == 1)
return 1;
else
{
a *= factorial(a-1);
return a;
}
}
let a=4
4 != 1 so the if portion is skipped for now.
4*=factorial(3)
3 != 1
3*=factorial(2)
2 != 1
2*=factorial(1)
1==1 so 1 is returned
2*1=2 so 2 is returned
2*3=6 so 6 is returned
6*4=24 so 24 is returned
The function doesn't get to the 'return a' until the factorial(a-1) returns a number which doesn't happen until a==1.
Recursive functions should be avoided at all costs because they get very complex. Large numbers would consume a lot of memory to do something as simple as a factorial.
4 != 1 so the if portion is skipped for now.
4*=factorial(3)
3 != 1
3*=factorial(2)
2 != 1
2*=factorial(1)
1==1 so 1 is returned
2*1=2 so 2 is returned
2*3=6 so 6 is returned
6*4=24 so 24 is returned
The function doesn't get to the 'return a' until the factorial(a-1) returns a number which doesn't happen until a==1.
Recursive functions should be avoided at all costs because they get very complex. Large numbers would consume a lot of memory to do something as simple as a factorial.
Blog Author: Vijay Kumar
No comments:
Post a Comment