I am trying to write a recursion program that will count the # of digits in an integer - and for some reason when I try to repeat the process - it won't reset the counter to zero - if I don't use a static int it doesn't work at all? what am I doing wrong?
int countDigits( int x )
The reason it does not reset is simply because you have declared the count variable as static. To make this function truly recursive, you don't need a counter variable, you simply need to implement what @vlad from moscow suggested; which I will unravel to a few lines:
ok... sorry - im confused... what happens to the 1? how is it passing the count of itterations of the call back... there is nothing to store the count or pass the count? C++ doesn't seem to do or know things "automatically"
Your code is strange to me - you use "?" & ":" in it - I assume your "?" is for my data - but the ":"? I have seen it in other code as well but we have not learned to do that - what does it mean?
It is the so-called conditional operator. For example
I would still like some sort of explanation to the 1+ part of this solution - when I step thru it appears that 1 has become the counter - but I don't see how, since its not declared. Just looking for some understanding - so that I can process it in my head as something other than "it just works... so use it"...
One thing you have to know about recursion is that it acts as a stack data structure.
Once you call the function again, the value left in the function (in this case 1 + )
is pushed unto the stack. Once the base case is reached, the last value returned is
in turn added to the first value at the top of the stack and that top value is popped from
the stack...Until one value is returned