Define recursive function. Write a program to find factorial of a number with recursive function.

Palak Patel08 May 2026
Define recursive function. Write a program to find factorial of a number with recursive function.

Define Recursive Function. Write a Program to Find Factorial of a Number Using Recursive Function

A recursive function is a function that calls itself repeatedly until a stopping condition is reached.

Recursion is commonly used to solve problems that can be divided into smaller similar subproblems.

Factorial Formula

The factorial of a number is calculated as:

n! = n × (n - 1)!

Example:

5! = 5 × 4 × 3 × 2 × 1 = 120

Algorithm

  • Take a number as input.
  • Create a recursive function named factorial().
  • If the number is 0 or 1, return 1.
  • Otherwise, return n × factorial(n - 1).
  • Display the factorial result.

C Program Using Recursive Function

#include <stdio.h>

int factorial(int n)
{
    if(n == 0 || n == 1)
    {
        return 1;
    }
    else
    {
        return n * factorial(n - 1);
    }
}

int main()
{
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    printf("Factorial of %d = %d", num, factorial(num));

    return 0;
}

Output Example

Enter a number: 5
Factorial of 5 = 120

Explanation of Program

Statement Purpose
factorial(n - 1) Function calls itself
if(n == 0 || n == 1) Stopping condition
return n * factorial(n - 1) Calculates factorial recursively

Advantages of Recursive Function

  • Code becomes shorter and cleaner.
  • Useful for mathematical and tree-based problems.
  • Easy to solve repetitive subproblems.

Conclusion

Recursive functions are powerful tools in programming for solving repetitive problems.

The factorial program is one of the most common examples used to understand recursion in C programming.