×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to find factorial using recursion

Factorial of a number is the product of that number with their all below integers.

For example (Factorial of 5) is: !5 = 5*4*3*2*1 = 120

Problem statement

Given an input number, find and print its factorial using recursion.

Algorithm to find factorial using recursion

Base Case:

  • If n is 0 or 1, return 1.

Recursive Case:

  • Otherwise, return n x factorial(n-1).

Pseudocode

function factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

C program to find factorial using recursion

/*C program to find factorial of a number 
using recursion.*/

#include <stdio.h>

// function for factorial
long int factorial(int n) {
  if (n == 1) return 1;
  return n * factorial(n - 1);
}

int main() {
  int num;
  long int fact = 0;

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

  fact = factorial(num);
  printf("Factorial of %d is = %ld", num, fact);
  printf("\n");
  
  return 0;
}

Output

Enter an integer number: 5
Factorial of 5 is = 120

C Recursion Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.