#include <iostream>
usingnamespace std;
int count_digits(int n)
{
if (n >= 0 && n < 10)
{
return 1;
}
elseif (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?
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 ) );