Factorial Program using for Loop in C++ | Factorial using Recursion function in C++



Factorial Program using Loop

Factorial Program in C++ using loop.
  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.    int i,fact=1,number;    
  6.   cout<<"Enter any Number: ";    
  7.  cin>>number;    
  8.   for(i=1;i<=number;i++){    
  9.       fact=fact*i;    
  10.   }    
  11.   cout<<"Factorial of " <<number<<" is: "<<fact<<endl;  
  12.   return 0;  
  13. }  
Output:
Enter any Number: 5  
 Factorial of 5 is: 120   

Factorial Program using Recursion

Factorial program in C++ using recursion.
  1. #include<iostream>    
  2. using namespace std;      
  3. int main()    
  4. {    
  5. int factorial(int);    
  6. int fact, value;    
  7. cout<<"Enter any number: ";    
  8. cin>> value;    
  9. fact = factorial(value);    
  10. cout<<"Factorial of a number is: "<<fact <<endl;    
  11. return 0;    
  12. }    
  13. int factorial(int n)    
  14. {    
  15. if(n<0)    
  16. return(-1); // if n is less than 0 it will return -1      
  17. if(n==0)    
  18. return(1);    
  19. else    
  20. {    
  21. return ( n*factorial(n-1) );        
  22. }    
  23. }  
Output:
Enter any number: 6   
Factorial of a number is: 720

Post a Comment

0 Comments