Example:
// num = 5;
void test (int num) {
cout << "Testing " << num << endl;
if (num > 0) {
cout << "Trying" << endl;
test(num - 1);
}
cout << "Returning " << num << endl;
}
When the "Testing and Trying" display 5 times. Then go to "returning", but
the thing is that NUM IS INCREMENTING and it stops at when num = 5.
my question is how num is incrementing?
Another question:
// num = 5
int test(int num) {
if (num == 0)
return 1;
else
return num * test(num -1)
}
how is it calculate? i know that the answer 120 becuase 5*4*3*2*1
but i dont see picture how is computer doing it.
2) I was having a bit of trouble wrapping my mind about this but it's actually pretty simple once you understand it.
Let's review: http://codepad.org/6wUMAw5F
Or for those who's school likes being a dick and blocking everything that seems to be useful on the internet (including its own site links), here's a snippet on the forum using code tags:
#include <iostream>
int test(int);
int main()
{
std::cout << test(5) << std::endl;
}
int test(int num)
{
if (num <= 0)
return 1;
else
{
std::cout << num;
if (num != 1)
std::cout << " * ";
else
std::cout << " = ";
return num * test(num -1);
}
}
So, this is actually pretty simple. It calls test given the argument integer 5. When it does this, it returns num * test(num - 1). test(num - 1) returns test( num - 1) and so on until num equals 0. So, in an extended version, its equivalent (as long as we pass 5 to test) to return num * test(4) * test(3) * test(2) * test(1) * test(0); It stops at test(0) because the function will return 1 instead of calling test again.
Thank You
The second is pretty much as i thought it is. i just not sure about it.
But the first one u miss my returning
void test (int num) {
cout << "Testing " << num << endl;
if (num > 0) {
cout << "Trying" << endl;
test(num - 1);
}
cout << "Returning " << num << endl;
}
when num is less than 0, the "Returning" statement excuate
the "Returning" statement it displays like this
Returning 0
Returning 1
Returning 2 // the num it got increment since there is no sign of incrementing
Returning 3
Returning 4
Returning 5