Challenge: Reverse Recursively

Lab C++ Beginner 10 points

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
Sample input available Sample output available
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
HOME LABS COMMUNITY DASHBOARD