Exercise 4-12

Adapt the ideas of printd to write a recursive version of itoa; that is, convert an integer into a string by calling a recursive routine.

We start with printd as a template, as it has a lot in common with the function we want to implement.

    /* printd:  print n in decimal */
    void printd(int n)
    {
        if (n < 0) {
            putchar('-');
            n = -n;
        }
        if (n / 10)
            printd(n / 10);
        putchar(n % 10 + '0');
    }

We first create the static integer i to act as the current index of s. i is static because we want its value to be saved when we call itoa recursively. Similar to printd, we recursively call itoa(n / 10, s) until n / 10 equals zero. When that happens, if n is negative (remember, the modulo operator retains signs), we set the first character of the string to be a minus sign. Then, we set s[i] to equal |n| % 10 + '0' and increment i after doing so. Finally, after i has been incremented, we set s[i] to \0. This element will be overwritten on every call of itoa except the last one, ensuring that the string is null-terminated.

    /* printd:  print n in decimal */
    void printd(int n)
    /* itoa:  convert n to characters in s */
    void itoa(int n, char s[])
    {
        static int i = 0;
    
        if (n < 0) {
            putchar('-');
            n = -n;
        }
        if (n / 10)
            printd(n / 10);
            itoa(n / 10, s);
        else if (n < 0)
            s[i++] = '-';
        putchar(n % 10 + '0');
        s[i++] = ((n >= 0) ? n : -n) % 10 + '0';
        s[i] = '\0';
    }