Factorial program in C++
Factorial Program in C++: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!. For example:
- 4! = 4*3*2*1 = 24
- 6! = 6*5*4*3*2*1 = 720
Here, 4! is pronounced as "4 factorial", it is also called "4 bang" or "4 shriek".
The factorial is normally used in Combinations and Permutations (mathematics).
There are many ways to write the factorial program in C++ language. Let's see the 2 ways to write the factorial program.
- Factorial Program using loop
- Factorial Program using recursion
Factorial Program using Loop
Let's see the factorial Program in C++ using loop.
- #include <iostream.h>
- #include <conio.h>
- void main()
- {
- int i,fact=1,number;
- cout<<"Enter any Number: ";
- cin>>number;
- for(i=1;i<=number;i++){
- fact=fact*i;
- }
- cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
- getch();
- }
Output:
Enter any Number: 5 Factorial of 5 is: 120
Factorial Program using Recursion
Let's see the factorial program in C++ using recursion.
- #include<iostream.h>
- #include <conio.h>
- void main()
- {
- int factorial(int);
- int fact,value;
- cout<<"Enter any number: ";
- cin>>value;
- fact=factorial(value);
- cout<<"Factorial of a number is: "<<fact<<endl;
- return 0;
- }
- int factorial(int n)
- {
- if(n<0)
- return(-1); /*Wrong value*/
- if(n==0)
- return(1); /*Terminating condition*/
- else
- {
- return(n*factorial(n-1));
- }
- }
Output:
Enter any number: 6 Factorial of a number is: 720
0 Comments