Answer:
#include <iostream>
using namespace std;
void recReverse(string exp)
{
if (exp.size() == 0) //check for empty string
{
return;
}
if (exp[0] == ' ')
{
recReverse(exp.substr(1)); //only subtracting, not printing the spaces
}
else
{
recReverse(exp.substr(1));
//subtracting the previously first element
cout << exp[0];
//printing new first element
}
}
int main()
{
string exp = "Hello There";
recReverse(exp);
return 0;
}
Explanation:
A recursive function calls itself and works kind of like a loop. A russian doll, if you will. The downside of this program is that if the statement becomes too long it becomes very slow. The upside is, that i some cases, it provides elegant solutions.
In the above code, we have first made sure that we don't have a blank string input. In case we do, we've made sure the function exits before doing any extra work. Then if the next element of the string is a space, we haven't printed it. Instead we've omitted the 'cout' and carried on with our recursion. Finally, in the else statement, we are printing the character along with subtracting it. Giving us our final recursive call backwards printing.