Help me understand this recursion please

I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int count_digits(int n)
{
    if (n >= 0 && n < 10)
    {
        return 1;
    }

    else if (n >= 10)
    {
        return 1 + count_digits(n / 10);
    }
}

int main()
{
    cout << "Number of digits in 456 is " << count_digits(456);
    cout << "\nNumber of digits in 7777 is " << count_digits(7777);
    cout << "\nNumber of digits in 4444444 is " << count_digits(4444444);

    cin.get();
    return 0;
}


I don't know how that is working. I mean, it works correctly and counts the digits in the numbers recursively, but I don't know how. I'm writing it down on paper trying to go through it step by step, but I'm not getting any closer to understanding it, and I think I'm even more confused now that I'm working it out on paper. Can someone explain how this works?
Let's look at a single case:

What happens when we call count_digits(1234);?

It does not pass the condition in line 7, but does pass the condition in line 12. Therefore it resolves as:
return 1 + count_digits( 123 );

When we look at 123, it does not pass the condition in line 7, but does pass the condition in line 12, so now
return 1 + ( count_digits(123) ); becomes
return 1 + ( 1 + count_digits(12) );

count_digits(12) does not pass the condition in line 7, but does pass the condition in line 12 so now:
return 1 + ( count_digits(123) ); becomes
return 1 + ( 1 + ( count_digits(12) ) ); which becomes
return 1 + ( 1 + ( 1 + count_digits(1) ) );

count_digits(1) passes the condition in line 7, so it returns 1 immediately. so now:
return 1 + ( count_digits(123) ); becomes
return 1 + ( 1 + ( count_digits(12) ) ); which becomes
return 1 + ( 1 + ( 1 + count_digits(1) ) ); which becomes:
return 1 + ( 1 + ( 1 + 1 ) );

The answer is 4.
Last edited on
Nice explanation! You made totally clear.
Thanks for the explanation, its making more sense now.
You're very welcome
Topic archived. No new replies allowed.