/***********************************************************************
The function reverse(string s) prints the string s in reverse order.
This implementation uses recursion. Note that we overload the
function print_reverse to allow it to be called without the length
argument.
***********************************************************************/
#include <iostream>
#include <string>
using namespace std;
void print_reverse(string s);
void print_reverse(string s, int k);
int main()
{
// Read string from user
string s;
cout << "Enter a string: ";
cin >> s;
// Print string in reverse
cout << "The reverse of '" << s << "' is '" ;
print_reverse(s);
cout << "'" << endl;
return 0;
}
// Call recursive print_reverse with entire string
void print_reverse(string s)
{
print_reverse(s, s.length());
}
// Recursive function to print string
void print_reverse(string s, int k)
{
cout << s[k-1]; // k-1 to shift to range [0,length-1]
if (k!=1)
print_reverse(s, k-1);
}