Complete the code to print the reversed string using a loop.
char str[] = "hello"; int len = 5; for (int i = len - 1; i >= [1]; i--) { printf("%c", str[i]); } printf("\n");
The loop should start from the last index (len - 1) and go down to 0 to print all characters in reverse.
Complete the code to swap characters for in-place string reversal.
char str[] = "world"; int len = 5; for (int i = 0; i < [1]; i++) { char temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; } printf("%s\n", str);
We only need to swap characters up to the middle of the string to reverse it in place.
Fix the error in the recursive string reversal function call.
void reverse(char *str, int start, int end) {
if (start >= end) return;
char temp = str[start];
str[start] = str[end];
str[end] = temp;
reverse(str, [1], end - 1);
}The recursive call should move the start index forward by 1 and the end index backward by 1 to continue swapping.
Fill both blanks to create a loop that copies characters from the end to the start in a new string.
char str[] = "abcde"; char rev[6]; int len = 5; for (int i = 0; i < [1]; i++) { rev[i] = str[[2] - i - 1]; } rev[len] = '\0'; printf("%s\n", rev);
The loop runs from 0 to len - 1, and the index for str is len - i - 1 to copy characters in reverse order.
Fill all three blanks to create a function that returns a new reversed string.
char* reverse_string(const char* str) {
int len = 0;
while (str[len] != '\0') {
len++;
}
char* rev = malloc(sizeof(char) * (len + 1));
for (int i = 0; i < [1]; i++) {
rev[i] = str[[2] - i - 1];
}
rev[[3]] = '\0';
return rev;
}The loop runs from 0 to len - 1, copying characters from the end to the start. The null terminator is placed at index len.
