In order to learn recursion, I want to count the number of decimal digits that compose an integer. For didactic purposes, hence, I would like to not use the functions from math.h
, as presented in:
I tried two ways, based on the assumption that the division of an integer by 10
will, at a certain point, result in 0
.
The first works correctly. count2(1514, 1)
returns 4
:
int count2(int n, int i){
if(n == 0)
return 0;
else
return i + count2(n / 10, i);
}
But I would like to comprehend the behavior of this one:
int count3(int n, int i){
if(n / 10 != 0)
return i + count3(n / 10, i);
}
For example, from count3(1514, 1);
I expect this:
1514 / 10 = 151; # i = 1 + 1
151 / 10 = 15; # i = 2 + 1
15 / 10 = 1; # i = 3 + 1
1 / 10 = 0; # Stop!
Unexpectedly, the function returns 13
instead of 4
. Should not the function recurse only 3 times? What is the actual necessity of a base case of the same kind of count2()
?