Reverse Word Order
Completed
Read a line of words (single spaces) and print the words in reverse order.
Input
One line.
Output
One line.
Example
Input
one two three
Output
three two one
Editor
C
Hints
Scan from the end; each time you hit a space (or the start), print the word after it.
Solution explanation
Working backwards with an end marker prints each word without extra buffers.
Show solution
#include <stdio.h>
#include <string.h>
int main() {
char s[300];
fgets(s, 300, stdin);
s[strcspn(s, "\n")] = '\0';
int end = strlen(s);
int first = 1;
for (int i = end - 1; i >= -1; i--) {
if (i == -1 || s[i] == ' ') {
if (!first) printf(" ");
for (int j = i + 1; j < end; j++) printf("%c", s[j]);
first = 0;
end = i;
}
}
printf("\n");
return 0;
}