in Doing Books

The C Programming Language (TCPL): Chapter 4

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

#include
#include

void switchchar(char s[], int i, int j)
{
char tmp;

tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}

void reverse(char s[])
{
static int i = 0;
static int len = 0;

if(i == 0)
{
len = strlen(s) - 1;
}

switchchar(s, i, (len - i));

i++;
if(i <= (len / 2)) { reverse(s); } } int main() { char str[] = "ABCDEF123456"; reverse(str); printf("%sn", str); return 0; }

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.