Recursion

Process of a function that calls itself.

 

Must have an ending point, or it will go into an infinite loop.

 

#include <stdio.h>

int factorial(unsigned int i)
{
   printf("Recursion: %dn", i);
   if(i <= 1)
   {
      return 1;
   }
   return i * factorial(i - 1);
}
int  main()
{
    int i = 5;
    printf("Factorial %d! = %dn", i, factorial(i));
    return 0;
}

Compile & run:

Recursion: 5
Recursion: 4
Recursion: 3
Recursion: 2
Recursion: 1
Factorial 5! = 120

Leave a Reply