Home > Software design >  How to give out a word backwards in c
How to give out a word backwards in c

Time:10-13

Can someone help me with my code. I have to create a program, where the user puts in a word and that word has to be given out backwards. My code doesn't really work, because the backward word puts out some random characters and then gives out the right word.

#include <stdio.h>

int main(){
    char word[10];
    printf("Please enter a word : ");
    scanf("%s", word);

    for (int i = 10; i >= 0; i--){
        if (word[i] !=0){
            printf("%c", word[i]);
        }
    }
    return 0;
}

CodePudding user response:

For starters this call of scanf

scanf("%s", word);

is unsafe. You need at least to specify the length of the entered string like

scanf("%9s", word);

The second problem is that the user can enter less than 9 characters. So this for loop

for (int i = 10; i >= 0; i--){

is incorrect. And moreover the index equal to 10 points to memory outside the array. So this if statement

if (word[i] !=0){

in any case wrong when i is equal to 10.

You need to find the length of the entered string.

The program can look the following way

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

int main( void )
{
    char word[10];

    printf( "Please enter a word : " );

    if ( scanf( "%9s", word ) == 1 )
    {
        for ( size_t n = strlen( word ); n != 0; --n )
        {
            putchar( word[n-1] );  
        }
        putchar( '\n' );
    }
}

CodePudding user response:

You're accessing outside the array, since your loop starts at i=10, but the last element of the array is word[9]. And if the user types less than 9 characters, you'll print uninitialized characters.

Use strlen() to determine how long the word is. Then subtract 1 from this to get the index of the last character.

for (int i = strlen(word)-1; i >= 0; i--)

You should also print a newline at the end.

  • Related