#include <stdio.h>
#include <string.h>
int main() {
char s[1001];
fgets(s, 1001, stdin);
for (int i = strlen(s) - 1; s[i] == '\n'; i--)
;
for (; i >= 0; putchar(s[i--]))
;
}
return 0;
}
The code reads a line of input, then attempts to remove the trailing newline and print the string in reverse. However, there is a problem with the variable scope and the loop logic.
- The variable `i` is declared inside the first `for` loop, so it is not accessible in the second `for` loop. You need to declare `i` before the loops so both can use it.
- The first loop condition `s[i] == '\n'` will only run if the last character is a newline, but the loop decrements `i` and checks again, which may go out of bounds if there is no newline. Think about how to correctly find the last character index before the newline.