Reverse String in C: Two Simple Methods

There are two methods for reversing the output of a string in the C language.

Option 1: Reverse the string by using a loop and a temporary variable.

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

void reverseString(char str[]) {
    int length = strlen(str);
    for (int i = length - 1; i >= 0; i--) {
        printf("%c", str[i]);
    }
}

int main() {
    char str[] = "Hello, World!";
    reverseString(str);
    return 0;
}

Option two: Reverse the string output recursively.

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

void reverseString(char str[], int start, int end) {
    if (start >= end) {
        return;
    } else {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        reverseString(str, start + 1, end - 1);
    }
}

int main() {
    char str[] = "Hello, World!";
    int length = strlen(str);
    reverseString(str, 0, length - 1);
    printf("%s", str);
    return 0;
}

Both methods can achieve reverse string output, the choice between them depending on personal preference and practical needs.

bannerAds