Jun 20, 2014 at 11:53am Jun 20, 2014 at 11:53am UTC
Well. I think if I write another one you'll understand.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream>
//In your case, the return make the code stop and call itself again. (because it's void)
//A better application is that:
unsigned factorial(unsigned number)
{
unsigned result;
if (number <= 1 ) return 1;
result = number * factorial(number - 1); // number * number - 1 * number - 2 .. * [number - (number - 1) = 1]
return result;
}
//So think on this recursion function:
// y = 10
//[sigma] x + y = (0 + 10) + (1 + 10) + (2 + 10) + (3 + 10) ... (10 + 10)
// x = 0
unsigned int sum(unsigned int start_, unsigned int end_)
{
if (start_ != end_ + 1)
return start_ + end_ + sum(start_ + 1, end_); //sum will be evaluated on the recursion call
else return 0;
}
//And try to understand it.
int main(int argc, char * argv[])
{
std::cout << "Factorial of 3. Expected result = 6\n(3x2x1 = 6)\n\n" ;
std::cout << "Calling factorial(3)... " << (factorial(3) == 6? "Passed" : "Failed" );
std::cout << "\n\n" << "Sum of 3. Expected result = 18\n[(0+3) + (1 + 3) + (2 + 3) + (3 + 3)] = 18\n\n" ;
std::cout << "Calling sum(0,3)... " << (sum(0,3) == 18? "Passed" : "Failed" );
std::cout << "\n\nFinal result of recursion functions: " << (sum(0,5) == 45 && factorial(5) == 120? "OK." : "Fail." );
}
Last edited on Jun 20, 2014 at 12:04pm Jun 20, 2014 at 12:04pm UTC