Skip to content

A clean solution to Exercise 4.13 #89

@ChenZhongPu

Description

@ChenZhongPu
#include <stdio.h>
#include <string.h>

// Recursive helper function to reverse the string in place
void reverse_recursive(char s[], int left, int right) {
    // Base case: if the left index has crossed the right, we're done.
    if (left >= right) {
        return;
    }

    // Swap the characters at the left and right ends
    char temp = s[left];
    s[left] = s[right];
    s[right] = temp;

    // Recursive step: call reverse on the inner substring
    reverse_recursive(s, left + 1, right - 1);
}

/* reverse: reverse string s in place */
void reverse(char s[]) {
    int len = strlen(s);
    if (len > 0) {
        reverse_recursive(s, 0, len - 1);
    }
}

int main() {
    char str1[] = "Hello, World!";
    printf("Original string: %s\n", str1);
    reverse(str1);
    printf("Reversed string: %s\n\n", str1);

    char str2[] = "recursion";
    printf("Original string: %s\n", str2);
    reverse(str2);
    printf("Reversed string: %s\n\n", str2);

    char str3[] = "a";
    printf("Original string: %s\n", str3);
    reverse(str3);
    printf("Reversed string: %s\n\n", str3);

    char str4[] = "";
    printf("Original string: %s\n", str4);
    reverse(str4);
    printf("Reversed string: %s\n\n", str4);

    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions