Recursive Functions for Processing the Digits of a Number
There are many problems involving the digits of a number, and many of them can be solved using a function – even a recursive one:
- the sum of the digits of a number; the sum of the digits of a certain type (even/odd, etc.);
- the number of digits; the number of digits of a certain type (even/odd, etc.);
- constructing a number using certain digits from the given number;
- etc.;
To create a recursive function that determines the required result, we use an algorithm of the following form:
- identify the base case;
- if we are in the base case, obtain the result directly;
- if we are not in the base case:
- solve the problem for the number without the last digit through a self-call;
- with the obtained result and the last digit, obtain the final result for the given number.
Of course, the above algorithm needs to be adapted to the specifics of the problem, but in most cases, it is of this type!
Example
To determine the sum of the digits of a number, proceed as follows:
- the function header will be: int sumcif(int n)
- the base case can be when the number is 0 (n==0). In this case, the result is 0;
- if n>0, determine the result for the number without the last digit: S = sumcif(n/10);
- the final result will be S + n % 10 – the sum of the digits of the number without the last digit, added to the last digit of n.
Put together, we get:
int sumcif(int n)
{
if(n == 0)
return 0;
else
{
int S = sumcif(n/10);
return S + n%10;
}
}