Beginner · Strings
Reverse a String
Read a word and print it backwards. Your first taste of character arrays — the C-style string, which is just a char array with a hidden terminator.
At a glanceRead the word into a char array, get its length with strlen, and print the characters from last to first — a C string is just a char array ending in a hidden '\0'.
Problem
Input: One word (no spaces), up to 99 characters.
Output: The same characters, reversed.
Sample:
| Input | Output |
|---|---|
hello | olleh |
Your solution
Custom input for "Run my input"
Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.
Stuck? Hints
Hint 1 — char array + strlen
char s[100]; cin >> s; reads one word. strlen(s) gives its length. Then loop from n-1 down to 0.
Hint 2 — Why stop at the terminator?
A C-style string ends with a zero byte. That is how functions know where the text ends.
Solution (try it first!)
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin >> s;
int n = strlen(s);
for (int i = n - 1; i >= 0; i--) cout << s[i];
cout << endl;
return 0;
}
It is the array cousin of Reverse a Number — same idea, different data type.
Deep dive
Why this works
A C-style string is an array plus a terminator. Reversing it in place with two indices — one from each end — is the pattern behind every in-place transform.
The cost
O(n) time, O(1) extra space in place; O(n) extra if you copy into a second array.
Where it goes wrong
- Calling strlen in the loop condition makes the whole thing O(n²). Cache the length once.
- Forgetting the terminator, or overwriting it, produces garbage past the end of the string.
Next step
The same array skills on characters: Count the Vowels.
Two things to remember
- Two indices closing in from both ends: the in-place reversal pattern.
- strlen inside a loop condition is a hidden O(n²).
🐞 This version fails — open it and try
Prints the array forward — never reverses
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin >> s;
int n = strlen(s);
for (int i = 0; i < n; i++) cout << s[i];
cout << endl;
return 0;
}