Print reverse of a string using recursion
To reverse a string using recursion we can create a function that will call iteself with substring of string after removing first element and break when the size of string passed is equals to zero.
Let's code this approach.
#include<bits/stdc++.h>
using namespace std;
void stringReverse(string s)
{
if(s.size() == 0)
return;
stringReverse(s.substr(1));
cout<<s[0];
}
int main()
{
string s = "HackersFriend";
stringReverse(s);
return 0;
}
dneirFsrekcaH
Explanation
Let's understand how it works.
During first call of stringReverse Funnction string is sliced and the rest of it is passed to recursive call of the function, this kind of recursive calls kept going on until the entire string is sliced and an empty string is passed to function call.
Once function gets an empty string it returns, and the line below recursive call is executed. i.e. the line cout<<s[0] now the first element of the string is printed, which is acutally the last element of the original string. Similarly, subsequest elements are elements of original string when reversed.
That's how it prints the string in reversed order.
If you want to see the working of program on every step, you can just add a print statement in the begining of the fucntion so that we can see what is being passed to the function, and we'll get a proper idea of what is going on inside it with every call.
Let's have a look into it.
#include<bits/stdc++.h>
using namespace std;
void stringReverse(string s)
{
cout<<s<<endl;
if(s.size() == 0)
return;
stringReverse(s.substr(1));
cout<<s[0];
}
int main()
{
string s = "HackersFriend";
stringReverse(s);
return 0;
}
HackersFriend
ackersFriend
ckersFriend
kersFriend
ersFriend
rsFriend
sFriend
Friend
riend
iend
end
nd
d
dneirFsrekcaH