**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:

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

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:

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

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:

int value = factorial(5);

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++

ISBN: 738453099

EAN: N/A

EAN: N/A

Year: 2007

Pages: 142

Pages: 142

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net