0
   // factorial calculator
   #include <iostream>
   using namespace std;

    long factorial (long a)
    {
      if (a > 1){

       return (a * factorial (a-1)); }//function calling itsself
     else
     return 0;
   }

    main ()
    {
     long number = 2;
      cout << number << "! = " << factorial (number);

    }

i am begginer learning objects and classes. i get some code from my context but its getting some error. how return statement is working when its value is 0 out put becomes 0 when it is return 1 output is 2. when it is return 3 output is 6 similar for 4 is 8.

Ali Almis
  • 35
  • 5
  • Please trace the recursion on paper (or with your debugger) for `factorial(2)`, for example, and you'll see your problem... – Ken Y-N Nov 18 '16 at 03:11

1 Answers1

0

Here's a calculator to compute factorial

#include <iostream>

using namespace std;

int Factorial(int long long a) {
    int long long Ans = 1;
    for (int x = 1; x <= a; x++) {
        Ans *= x;
    }

    return Ans;
}

int main() {

    int Input;
    cin >> Input;   

    if (Input > 0) {
        cout << Factorial(Input);
    }
}

Calling a function from within itself is generally considered bad practice, so avoid it. Use long long if you need larger numbers. Also, try to provide more information about your question.

Vincent Thacker
  • 393
  • 1
  • 13