Recursive Functions


Recursive functions can be used in C and also in C++. A function is recursive, if it calls itself directly or indirectly through another function. Each time the recursive function is called, it begins over again. A new set of arguments and local variables are created on the stack. There will be one set of variables for each call. Because there is a set of variables for each call, the programmer must guard against permitting too deep a call for the available stack memory. In particular, care must be taken not to have an infinite call.

For example:

image from book

 int new_gcd(int numb1, int numb2) {    return (numb1 < 0)? (new_gcd(-numb1,numb2)):       ((numb2 == 0) ? numb1:       new_gcd(numb2 , numb1 % numb2)); } 

image from book

This function returns the greatest common divisor of the two numbers: numb1 and numb2. See NEWGCD.CPP

Another example of recursive functions is the following function:

image from book

 unsigned long factorial(int numb) {   return (numb==0) ? (1) :(numb * factorial(numb-1)); } 

image from book

This function will return the factorial of the number: numb. In mathematics we would represent this by numb!. A call to this function could be:

image from book

 int value = factorial(5); 

image from book

in which case value would be 120 that is 5!. In order to execute this call there would need to be 6 copies of numb created on the stack, one for each number 0 up to 5. However there will be only one copy of the function in memory. See NEWFACT.CPP




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net