Adsense 728 * 15

Search

Custom Search

C Program to Print Factorial of a Number using Recursion

Write a C program to print factorial of a number using recursion.  In this program, we have to write a code which takes an input number and print factorial of a number using recursion.

Before solving this problem, let's first understand what is recursion? And the difference between recursion and iteration.

What is Recursion?


In Recursion, A function calls itself until the base condition is reached. Using recursion, we can write much cleaner and shorter as compared to iterative code. You can learn more about recursion using following tutorials.


MCQ on Recursion for Practice

In this tutorial, we use recursion to solve this problem. In my previous post, i have explained how to solve this problem using iteration.

C program to print factorial of a number

Java program to print factorial of a number

C++ program to print factorial of a number

C Program to Print Factorial of a Number using Recursion


C Program to Find Factorial of a Number using Recursion



Let's write a c code to print factorial of a number using recursive approach. In this program, first we take input number from a user then we call a calculateFactorial() method to calculate factorial of a number.


#include <stdio.h>

int calculateFactorial (int num) {
 
  /* If number is zero or 1 then return 1 */

  if ( num == 0 || num == 1) {
   
     return 1;
   
   } 
  
   /* Recursive function call */

   return num * calculateFactorial(num-1);
}

int main() {
 
  int num, fact = 0;
 
  printf ("Enter a number \n");
  scanf ("%d", &num);
 
  /* Function call */

  fact = calculateFactorial(num);
 
  printf ("Factorial of a number %d is %d ",num,fact);
  return 0;
}


Output :

Enter number :  5

Factorial of a number 5 is 120


Explanation :

Suppose you have entered 5 so how this program is going to be executed.

5 * calculateFactorial (5-1)
5 * 4 * calculateFactorial (4-1)
5 * 4 * 3 * calculateFactorial (3-1)
5 * 4 * 3 * 2 * calculateFactorial (2-1)
5 * 4 * 3 * 2 * 1 

No comments:

Post a Comment