Recursive String Reverse
C
Hard
3 views
Problem Description
Use WITHOUT loop recursively to reverse the string. Clearly define base case and recursive case. Compare with Iterative approach.
Official Solution
#include <stdio.h>
#include <string.h>
/* Recursive function to reverse a string in place */
void reverseRecursive(char str[], int start, int end) {
/* Base case: start >= end -> stop recursion */
if (start >= end)
return;
/* Swap characters at start and end */
char temp = str[start];
str[start] = str[end];
str[end] = temp;
/* Recursive call for inner substring */
reverseRecursive(str, start + 1, end - 1);
}
/* Iterative reversal using loop */
void reverseIterative(char str[]) {
int i, j;
char temp;
int n = strlen(str);
for (i = 0, j = n - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
int main() {
char str1[100], str2[100];
printf("Enter a string: ");
scanf("%s", str1);
/* Copy string for iterative method */
strcpy(str2, str1);
/* Recursive reversal */
reverseRecursive(str1, 0, strlen(str1) - 1);
printf("Reversed string (recursive): %sn", str1);
/* Iterative reversal */
reverseIterative(str2);
printf("Reversed string (iterative): %sn", str2);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!