Factorial Program using Loop , using Recursion

 

//  using Loop

#include <iostream>
using namespace std;
int 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;
return 0;
}

run by    http://www.cpp.sh/

 

// using Recursio

#include<iostream>

using namespace std; 

int 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));
      }
}

 

refer  : https://www.javatpoint.com/factorial-program-in-cpp

 

上一篇:函数定义


下一篇:递归函数