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:


To create a recursive function that determines the required result, we use an algorithm of the following form:


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:


Put together, we get:

int sumcif(int n)
{
    if(n == 0)
        return 0;
    else
    {
        int S = sumcif(n/10);
        return S + n%10;
    }
}

Accessibility Options

Color Contrast

Text Size

Text Spacing

Reading Aids