Challenge: Reverse Recursively
Completed
Read a line of text and print it backwards using a recursive function (no reverse()).
Input
One line of text (at most 300 characters).
Output
The text reversed.
Example
Input
stressed
Output
desserts
Editor
C++
Hints
Print the last character, then recurse on the part before it.
Base case: index below 0.
Solution explanation
Passing an index instead of copying substrings keeps it O(n).
Show solution
#include <iostream>
#include <string>
using namespace std;
void printBackwards(const string& s, int i) {
if (i < 0) return;
cout << s[i];
printBackwards(s, i - 1);
}
int main() {
string s;
getline(cin, s);
printBackwards(s, (int)s.size() - 1);
cout << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module