Calculate Factorial of a Number Using Recursion in C

Exercise:

Write a C Program to find factorial of a number using recursion.

Click Here to View the Solution!
#include<stdio.h>
long int Factorial(int num);

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d",&num);
    printf("Factorial of %d = %ld", num, Factorial(num));
    return 0;
}

long int Factorial(int num) {
    if (num>=1)
        return num*Factorial(num-1);
    else
        return 1;
}
Click Here to View the Output!
Enter a positive integer: 5 
Factorial of 5 = 120 
Click Here to View the Explanation!
  • This program is used to calculate the factorial of a number using recursion.
  • A long int type function multiplyNumbers(int num) is declared.
  • In main(), The program requests the user to enter a positive integer and stores it in the variable num using the scanf() function.
  • The function multiplyNumbers is initially called from the main method with the entered number passed as an argument to the function.
  • Outside main, the function multiplyNumbers is initialized which will take num only is it is greater than or equal to 1.
  • The input num is multiplied with the multiplyNumbers function which will hold a number less than num (num - 1) in a recursive call.
  • In every recursive call, the value of the parameter will decrease by 1.
  • When the value of num will become less than 1, the recursive calls will end and the factorial of the number will be returned to main method for printing.
%d bloggers like this: