cstringreverseswapreversing

Reversing the string without library function


The code got compiled successfully. but I can't reverse the string. since I am a beginner-level programmer, I can't really figure out the mistake I made.

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

int main() {      
    int temp, i, j, length;
    char name[20], name1[20];

    printf(" Enter string \n");
    scanf("%s", name);
    length = strlen(name);
    printf(" %d", length);
    for (i = length - 1; i >= 0; i--) {
        name1[length - i] = name[i];
    }
    printf("%S ", name1);
    
    return 0;
}

Solution

  • Here are some issues in your code:

    Here is a modified version:

    #include <stdio.h>
    
    int main() {      
        char name[20], name1[20];
        int i, length;
    
        printf(" Enter string:\n");
        if (scanf("%19s", name) == 1) {
            length = strlen(name);
            printf("%d\n", length);
            for (i = 0; i < length; i++) {
                name1[length - i - 1] = name[i];
            }
            name1[length] = '\0';
            printf("%s\n", name1);
        }
        return 0;
    }