C++ Recursion Issue
- by stupidmonkey
Hi guys,
I feel a little dumb asking this, but here we go...
When trying to follow the Recursion example at the following website http://www.cplusplus.com/doc/tutorial/functions2/, I ran into a road bump that has me perplexed.
I altered the code slightly just to get my head around the code in the recursion example and I pretty much have my head around it, but I can't figure out why the variable 'n' increments in 'Pass B' when I have not told the program to increment 'n'.
Could you please help explain this?
#include <stdlib.h>
#include <iostream>
using namespace std;
long factorial (long n)
{
if (n > 1)
{
long r(0);
cout << "Pass A" << endl;
cout << "n = " << n << endl;
cout << "r = " << r << endl;
r = n * factorial (n-1);
cout << "Pass B" << endl;
cout << "n = " << n << endl;
cout << "r = " << r << endl;
return (r);
}
else
return (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number) << endl;
system ("pause");
return 0;
}