Program to Find Factorial of a Number using Iteration

bookmark

  1. #include<iostream>
  2. using namespace std;
  3. class fact
  4. {
  5. public:
  6.     /*
  7.      * Function to find the factorial
  8.      */
  9.     int factorial(int n)
  10.     {
  11.         int i;
  12.         int pro = 1;
  13.         for(i = n; i > 1; i--)
  14.         {
  15.             pro = pro * i;
  16.         }
  17.         if(n == 0)
  18.         {
  19.             pro = 1;
  20.         }
  21.         return pro;
  22.     }
  23. };
  24. /*
  25.  * Main function
  26.  */
  27. int main()
  28. {
  29.     fact f;
  30.     int n;
  31.     cout<<"Enter the number whose factorial is to be calculated\t";
  32.     cin>>n;
  33.     cout<<"\nFactorial of "<<n<<" is = "<<f.factorial(n);
  34.     return 0;
  35. }

 

Output

 

1. Enter the number whose factorial is to be calculated    5
 
   Factorial of 5 is = 120
2. Enter the number whose factorial is to be calculated    0
 
   Factorial of 0 is = 1