Definition
Recursive function is a function which contains a call to itself.
Why recursive function
Recursive function allows you to divide your complex problem into identical single simple cases which can handle easily. This is also a well-known computer programming technique: divide and conquer.
Warning of using recursive function
Recursive function must have at least one exit condition that can be satisfied. Otherwise, the recursive function will call itself repeatly until the runtime stack overflows.
Example of using recursive function
Recursive function is closely related to definitions of functions in mathematics so we can solving factorial problems using recursive function
All you know in mathematics the factorial of a positive integer N is defined as follows:
N! = N*(N-1)*(N-2)…2*1;
Or in a recursive way:
N! = 1 if N <=1 and N*(N-1)! if N > 1
The recursive function to calculate factorial
03 | int factorial(unsigned int number) |
07 | return number * factorial(number - 1); |
12 | printf ( "factorial of %d is %d" ,x,factorial(x)); |
The output of program
factorial of 5 is 120
In theory, all recursive functions can be rewritten by using iteration. In case number of recursive calls exceeded, the runtime stack can be overflow, you have to implement your recursive function using iteration. for example we can rewrite the factorial calculation using iteration as follows:
1 | int factorial(unsigned int number){ |
0 comments:
Post a Comment