/* * reverse a string recursively * * Matt Bishop, ECS 36A, Fall 2019 */ #include #include /* * reverse str recursively * this works by swapping the first and last character * then reversing what's between them, stopping when * there are 0 or 1 characters to reverse * * str = array containing (sub)string to reverse * b = index of first element in s(sub)string to be reversed * e = index of last element in s(sub)string to be reversed */ void reverse(char *str, int b, int e) { char tmp; /* used to swap two chars */ /* base case; if 0 or 1 character, return */ if (b >= e) return; /* now swap the beginning and end character */ tmp = str[b]; str[b] = str[e]; str[e] = tmp; /* and reverse the middle */ reverse(str, b + 1, e - 1); } /* * the program to run */ int main(void) { char str[100]; /* input string */ /* read in a line, and clobber any trailing newline */ if (fgets(str, 100, stdin) == NULL) return(1); if (str[strlen(str)-1] == '\n') str[strlen(str)-1] = '\0'; /* say what the string is */ printf("'%s' reversed is ", str); /* now reverse it and say what that is */ reverse(str, 0, strlen(str)-1); printf("'%s'\n", str); /* bye! */ return(0); }