To output the C-language strings in reverse order

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

#include <stdio.h> // output in reverse string order
int main() {
    char sarr[] = "banana";
    for (int i = 0; i < 10; i++) {
        if (sarr[i] == '\0')
            break;
        sarr[i] = sarr[5 - i];

        printf("%c\n", sarr[i]);
    }
    return 0;
}

I want to print bananas in reverse order as ananab, but it's printed as ananana Please tell me how to correct it to print it out properly! Thank you

c c++ array

2022-09-20 08:43

1 Answers

Please refer to the code below.

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

int main()
{
    char str[] = "banana";
    int len = strlen(str);

    for (int i = 0; i < len; i++)
        printf("%c", str[(len - 1) - i]);

    printf("\n");

    return 0;
}


2022-09-20 08:43

If you have any answers or tips


© 2022 pinfo. All rights reserved.