Loading your workspace…
Loading your workspace…
Read a line of text and reverse it in place, without using any string library function.
#include <stdio.h>
int main(void) {
char text[200];
int length = 0, i;
char temp;
printf("Enter a string:\n");
if (fgets(text, sizeof text, stdin) == NULL) {
printf("Error: no input\n");
return 1;
}
while (text[length] != '\n' && text[length] != '\0') {
length++;
}
text[length] = '\0';
for (i = 0; i < length / 2; i++) {
temp = text[i];
text[i] = text[length - 1 - i];
text[length - 1 - i] = temp;
}
printf("Reversed: %s\n", text);
return 0;
}
Input
programOutput
Enter a string:
Reversed: margorpInput
aOutput
Enter a string:
Reversed: aSwapping from both ends works in place, so no second array is needed. The loop runs only half the length, because each swap handles two characters.
The length is found by hand with a loop that stops at the newline or the terminator, which is exactly the job strlen does in the library.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
program
Expected output
Enter a string: Reversed: margorp
a
Expected output
Enter a string: Reversed: a
Each iteration swaps a pair, so going past the middle would swap the pairs back.
length - 1, because the characters occupy positions 0 to length - 1 and the terminator follows.
fgets stores the newline; overwriting it with the terminator makes the printed string end cleanly.
It holds one character during the swap.
O(n): each character is visited at most once during the swaps.
Back to all RCU 21BCA1C1P lab programs.