C Program to Find Factorial Using Recursive Function

A recursive function is a function defined in terms of itself via self-calling expressions. This means that the function will continue to call itself and repeat its behavior until some condition is satisfied to return a value.

Factorial Using Recursive Function

Program: Factorial of a given number using recursive function.
Author: Codesansar
Date: Jan 22, 2018

int fact(int n); /* Function Definition */

void main()
 int num, res;
 printf("Enter positive integer: ");
 res = fact(num); /* Normal Function Call */
 printf("%d! = %d" ,num ,res);
int fact(int n) /* Function Definition */
 int f=1;
 if(n <= 0)
  f = n * fact(n-1); /* Recursive Function Call as fact() calls itself */


Enter positive integer: 5↲
5! = 120

Working of above recursive example can be illustrated using following diagrams:

Recursion Examples
Figure: Illustration of Recursive Function


  1. /* ... */: A multi-line comment providing program details including purpose, author, and date.
  2. #include<stdio.h> and #include<conio.h>: Include necessary header files for input-output and console manipulation.
  3. int fact(int n);: Declare the prototype of the fact function.
  4. void main(): Start of the main function.
  5. int num, res;: Declare variables to store user input and the factorial result.
  6. clrscr();: Clear the console screen.
  7. printf("Enter positive integer: ");: Prompt the user to enter a positive integer.
  8. scanf("%d", &num);: Read user input and store it in num.
  9. res = fact(num);: Call the fact function and assign the result to res.
  10. printf("%d! = %d", num, res);: Display the input number and its factorial.
  11. getch();: Wait for user input to continue.
  12. int fact(int n): Start of the fact function.
  13. int f = 1;: Initialize a local variable f to store the factorial result.
  14. if (n <= 0): Check if n is less than or equal to 0.
  15. return 1;: Return 1 if n is negative or 0.
  16. else: Execute the following block if n is positive.
  17. f = n * fact(n - 1);: Calculate factorial recursively using f = n * fact(n - 1).
  18. return f;: Return the calculated factorial value.

Note: The use of conio.h and its functions may not be compatible with all compilers and systems.