Write a program to print factorial of a number using recursion in C. In this program, we have to write a code which takes an input number and print factorial of a number using recursion.
MCQ on Recursion for Practice
In this tutorial, we are going to use recursion to print factorial of a number. In my previous post, i have explained how to print factorial of a number in c using iterative approach.
C program to print factorial of a number
Java program to print factorial of a number
C++ program to print factorial of a number
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.
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
Before solving this problem, let's first understand what is recursion? And the difference between recursion and iteration.
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.
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 are going to use recursion to print factorial of a number. In my previous post, i have explained how to print factorial of a number in c using iterative approach.
C program to print factorial of a number
Java program to print factorial of a number
C++ program to print factorial of a number
Print Factorial of a Number using Recursion in C
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