On Sat, 21 Oct 2006 16:47:07 GMT in comp.lang.c++, mj
<jemisonsoftware@earthlink.netwrote,
Quote:
>I understand the syntax:
void counter(int End)
{
cout<< " ";
cout<< End;
if( End != 0 ){
counter(End-1);
}
}
>My brain seems to get tangled with trying to visualize the way the code
>coils and uncoils. I have stepped through this twenty or thirty times
>but I suppose I am looking for some caveat to help gel the concept.
|
How to gel the concept? Well, I don't know any simple answer except
to keep trying. Looking at it from different viewpoints helps, so
here's one:
Imagine a sheet of paper. On it is drawn a rectangle representing
an activation of counter(). I'm going to start by calling
counter(3), so the rectangle contains shorthand like
counter(3) {
cout << 3;
counter(2);
}
Now when you get to the counter(2) call above, take an imaginary
Post-it (trademark 3M) note and stick it down over the rectangle.
On it is written:
counter(2) {
cout << 2;
counter(1);
}
Naturally, there will be another Post-it to go on top of that, on
which says:
counter(1) {
cout << 1;
counter(0);
}
The final Post-it says:
counter(0) {
cout << 0;
// done
}
Since "if( End != 0 )" was not satisfied this time, there is no
additional Post-it on top of that. Instead you get to the }, peel
off the Post-it, and you are back at the previous one. But there is
nothing left to do there either, so peel it off too. And the next,
and the next, until you are all the way back to the original.
Any better?