Exercise 4-13

Write a recursive version of the function reverse(s), which reverses the string s in place.

This is the reverse function from section 3.5, which is written using an iterative approach.

    /* reverse:  reverse string s in place */
    void reverse(char s[])
    {
        int c, i, j;
    
        for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
            c = s[i];
            s[i] = s[j];
            s[j] = c;
        }
    }

The first thing we notice is that i is an index, so we make it static so that its value is preserved between calls. j is an index too; however, its definition requires the use of the function strlen, and the return value of a function cannot be used in the definition of a static variable. Luckily, we can still make j a non-static variable by assigning the value strlen(s) - 1 - i, which is functionally the same.

After the variables have been defined, as long as i is less than j, we swap the variables, increment i, and call reverse again.

    /* reverse:  reverse string s in place */
    void reverse(char s[])
    {
        int c, i, j;
        static int i = 0;
    
        for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
        j = strlen(s) - 1 - i;
        if (i < j) {
            c = s[i];
            s[i] = s[j];
            s[j] = c;
            ++i;
            reverse(s);
        }
    }