Recursive functions in C Programming

  • A function which calls itself is called a Recursive function.
  • It also means that some statement in that function's body calls to same function.
  • While using the recursive functions, it is important to be careful to define the exit condition from the function or then it may result into an infinite loop.
  • The recursive functions are very useful for solving mathematical problems.
  • They are used for calculating factorial of a number, fibonacci series etc.

Example: Write a program to find the factorial of a number using a function.

#include <stdio.h>
int factor (int);
void main()
{
     int x = 5, fact;
     fact = factor(x);
     printf("\n Factorial is = %d",fact);
}
int factor (int y)
{
    int a;
    if (y == 1)
        return 1;
    else
        a = y * factor(y-1);
    return (a);
}


Output:
Factorial is = 120

factorial