I want to print a string backwards. But my code seems to count down the alphabet from the last letter in the array to the first letter in the array instead of counting down the array itself and spitting out each letter in the array.
My code,
#include <stdio.h>
#include <string.h>
int main(void) {
char word[50];
char end;
char x;
printf("Enter a word and I'll give it to you backwards: ");
scanf("%s", word);
end = strlen(word) - 1;
for (x = word[end]; x >= word[0]; x--) {
printf("%c", x);
}
return 0;
}
Any suggestions? Thank you.
What you have loops between the array element values. You want to loop between the array indexes. Update your loop to the following:
Note that this goes from the last index to zero and output the character at that index. Also a micro-optimization in the for loop using pre-decrement.