Ankit Sharma
Ankit Sharma

Reputation: 663

C++ Digit Counting Weird Error

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

Answers (3)

MrPickles
MrPickles

Reputation: 1445

Recursive functions require two things:

  1. A terminating condition
  2. A reducing clause

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

unxnut
unxnut

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

WorldSEnder
WorldSEnder

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

Related Questions