Ali Almis Ali Almis - 1 year ago 71
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download