Ian Ian - 3 months ago 24
C++ Question

Why does return not work?

I am a beginner in c++ and I am trying to write factorial using recursion.
But, somehow the

return
won't work. This is my code:

#include <iostream>

using namespace std;

int factorial(int num) {
if(num == 1) {
return 1;
}
return num * factorial(num - 1);
}

int main() {
int num;
cout << "Please enter a number and I will do its factorial : ";
cin >> num;
factorial(num);
}


Can anyone tell me why the
return
won't work?

By the way I am using sublime on the mac.

Thanks,

Answer

Return works perfectly, it's just that your code is not using it.

The call to factorial(num) produces no output, just the return value. If you want to see it printed, add cout << factorial(num) << endl;