Program 312: Factorial of a number using Recursion
Output:
#include<stdio.h> int GetFactorial(int number); main() { int number,factorial; printf("Enter a number for knowing it's factorial\n"); scanf("%d",&number); factorial=GetFactorial(number); printf("%d!=%d\n",number,factorial); } int GetFactorial(int number) { if(number>0) { return number*GetFactorial(number-1); } else { return 1; } }Explanation:
- This program starts with initializing :
- number → To store given number to get Factorial
- factorial →Used to store output
- int GetFactorial→ Declaration of function
printf("Enter a number for knowing it's factorial\n"); scanf("%d",&number);
To take input from userfactorial=GetFactorial(number);
Calling GetFactorail Function and received output from the called function(i.e GetFactorial) will be sored in factorialint GetFactorial(int number) { if(number>0) { return number*GetFactorial(number-1); } else { return 1; } }
Now lets take a number 4 to get factoraial of 4.
now number is greater than 0(i.e 4>0) is true so if part is executed- Now
- return 4*GetFactorial(4-1);
- GetFactorial(3)---> return 3*GetFactorial(3-1)
- Substitute 3*GetFactorial(3-1) in Step 1
- So Step 1 will be return 4*3*GetFactorial(3-1)
- Now again GetFactorial(2)--->return 2*GetFactorial(2-1)
- So Step 4 will be return 4*3*2*GetFactorial(2-1)
- GetFactorial(1)--->return 1*GetFactorial(1-1)
- So again Step 6 will be return 4*3*2*1*GetFactorial(1-1)
- As GetFactorial(0)-->Since if(0>0) is false else part will be executed.So it will return 1.
- So Step 8 will be return 4*3*2*1*1
- Finally it returns value of 4*3*2*1*1=24
- factorial=24 and this will be printed as output
Output:
factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
ReplyDeletefactorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.