Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C

Learn step by step



C-Recursion

Recursion occurs when a function contains within it a call to itself. Recursion can result in very neat, good looking code that is intuitive to follow. It can also result to very large amount of memory being used if the recursion gets too deep

Common examples of where recursion is used :

  • Data structures which are recursive in nature such as binary trees, linked lists, etc.
  • Exploring possible scenarios in some games such as chess

Recursion always consists of two main parts. Frist terminating case that indicates when the recursion will finish and a call to itself that must make progress towards the terminating case.


#include <stdio.h>
unsigned int multiply(unsigned int x, unsigned int y)
{
if (x == 1)
{
/* Terminating case */
return y;
}
else if (x > 1)
{
/* Recursive step */
return y + multiply(x-1, y);
}

/* Catch scenario when x is zero */
return 0;
}

int main() {
printf("3 times 5 is %d", multiply(3, 5));
return 0;
} RUN



Related Videos