Home » Interview Questions » String Interview Questions » Print Reverse of a string (Recursion)

Print Reverse of a string (Recursion)


()

Print the reverse of a string using recursion.

Example

a) Input string : Sachin
Output : nihcas

b) Input string : Code
Output : edoC

Time complexity : O(n)

Algorithm

Create Reverse function to reverse string recursively
In this function,

a. It takes string pointer (str) as input.

b. It calls itself (recursively) with next location to passes pointer (str+1).

c. Continue recursion till it reaches the end of the string.

d. After all functions accumulated in stack print char at passed pointer.

e. Return one after one.

Algorithm working

C++ Program

#include <bits/stdc++.h>

using namespace std;

//Recursive function to reverse a string
void Reverse(char *str)
{
   if(*str)
   {
       Reverse(str+1);
       cout<<*str;
   }
}
 
//Main function
int main()
{
   char string[] = "code";
   cout<<"Input string: ";
   for (int i = 0; i < strlen(string); ++i)
   {
     cout<<string[i];
   }
   cout<<"\nOutput string after reversing: ";
   Reverse(string);
   return 0;
}

Try It

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Isomorphic Strings
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions