What are recursive functions used for?

  • Context: C/C++ 
  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    Functions
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
ineedhelpnow
Messages
649
Reaction score
0
Hi :o

Recursion. Recursive functions. What are they used for and how they helpful?
 
Physics news on Phys.org
Technically, a recursive function is a function that makes a call to itself. To prevent infinite recursion, you need an if-else statement (of some sort) where one branch makes a recursive call, and the other branch does not. This branch that does not make a recursive call becomes the terminating condition. Mathematically it should have a recursive definition.

for an example we know

factorial (1) =1

factorial ( n) = factorial (n-1) * n for n > 1

this can be coded as

#include <stdio.h>

int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}

this can be converted to

int factorial(unsigned int i)
{
int product = 1;
while (i) {
product = product * i;
i--;
}
return product;
}SOme times it may not be easy to convert particlularly for mutually recursive function say parsing of expression and so on and it is best to leave it as it is.
 
Last edited: