Word in reverse order

Asked

Viewed 135 times

0

I’m doing an exercise where I have to make the word given with input exit in reverse order.

I start by counting the number of letters you have in the typed word (commented on in the code). After counting the number of letters in the word I pass this value (number of letters) to another loop which will display the word in reverse order. For example: if the word is "test" I will have l = 5, passing the value from L to I, the order of print in the loop would be subscript 5 of the array name, then 4, then 3... but that’s not working.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, l = 0;
char name[50];
printf("Tell me a word: \n");
scanf("%s", name);
for( i = 0; name[i] != '\0'; i++){  /* até aqui o código irá simplesmente 
contar o number de letras na palavra digitada*/
l++;
}
if(name[i] == '\0'){
printf("The number of letters is %d\n", l); /* o programa só funciona até
aqui*/
}
printf("The word is the reverse order is\n"); 

for( i = l; i != 0; i--){
printf("%d", name[i]);
}
return 0;
}
  • 3

    It would be good to click on [Edit] and add your question in the question before the code. In the middle of the comments it is even difficult to notice. And it pays to explain a little better, so that it becomes easier for the staff to help.

  • 1

    Try to explain the problem. Read on [Ask], visit [tour] and [help] if necessary. Follow Bacco’s hint and try [Dit] the question to explain your doubt, in the current form, becomes difficult to understand.

1 answer

2


There are two errors: it seems that you did not understand what was answered in previous question who needs to use the %c to display characters; and he must consider position 0 as one of the characters to be printed, then he must use the operator >= and not !=. I take the opportunity to simplify and organize the code.

#include<stdio.h>
#include<stdlib.h>
int main() {
    char name[50];
    printf("Tell me a word: \n");
    scanf("%s", name);
    int i;
    for (i = 0; name[i] != '\0'; i++);
    if (name[i] == '\0') printf("The number of letters is %d\n", i);
    printf("The word is the reverse order is\n");
    for (int j = i; j >= 0; j--) printf("%c", name[j]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks! sorry, I understood the need to use the %c, it’s flawed mistake, but thanks again!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.