Reputation: 663
I have a very weird error. I have a very simple digit counting function. The function is going in an infinite loop if I do this:
int numOfDigits(int num, int count)
{
while(num != 0) {
count++;
numOfDigits(num/10, count);
}
return count;
}
But it works this way:
int numOfDigits(int num, int count)
{
while(num != 0) {
count++;
num /=10;
numOfDigits(num, count);
}
return count;
}
I tried using gdb but couldn't figure out. I'm compiling with g++ on Ubuntu 14.04.
Upvotes: 1
Views: 58
Reputation: 1445
Recursive functions require two things:
In your first example, you had the terminating condition num != 0
...but not the reducing clause as @WorldSEnder pointed out (num
was totally unaffected).
Also, there's no rule against iteration in recursion...but it usually makes things more complicated than it should be.
Upvotes: 0
Reputation: 8839
int numOfDigits(int num, int& count)
{
if(num != 0) {
count=1+numOfDigits(num/10, count);
}
return count;
}
I have changed count
as being passed by reference though it is not really required. You have the while
loop that goes on infinitely because num
is not modified in that context. You are mixing iteration and recursion.
Upvotes: 4
Reputation: 5054
while(num != 0) {
count++;
numOfDigits(num/10, count);
}
This while-loop never terminates, because num is never actually modified. Thus it will never exit the loop if the condition wasn't false in the first place.
Upvotes: 4