Ali Almis Ali Almis - 23 days ago 8
C++ Question

putting different values in return statement of c++

// 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.

Answer

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.