Kodewick
Start learning →
Basic←→0 / 50

Reverse a string

#041Basicj = strlen(s) - 16 min

Flip a string in its own char array: i points at the first character, j at the last; swap them, then move both toward the middle. abcde becomes edcba. Note: char a[] = "abcde" is an array you can change; the string that char *p = "abcde" points to can't be changed. Finish reverse(s); it shows two flipped strings.

Should show
edcba
dc21BA
main.c
#include <stdio.h>
#include <string.h>

void reverse(char s[]) {
    int i = 0;
    int j = 0;
    // your code here: make j point at the last character
    while (i < j) {
        // your code here: swap s[i] and s[j]
        i++;
        j--;
    }
}

int main(void) {
    char a[] = "abcde";
    char b[] = "AB12cd";
    reverse(a);
    reverse(b);
    printf("%s\n", a);
    printf("%s\n", b);
    return 0;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.