+92 332 4229 857 99ProjectIdeas@Gmail.com

How to reverse a string recursively (C++ Tutorial)


Reverse a string recursively
ReverseRecursive() takes 3 input parameters; first is the string, second and third are the index variables.It reverses the string recursively and returns the reversed string.
Example
For example. if the input to this function is Saad Bin Saulat, then it will return taluaS niB daaS.
Code of ReverseRecursive()

char * ReverseRecursive( char str[] , int i , int j )
{
      if( i < strlen( str ) / 2 )
      {
            Swap( &str[i++] , &str[j--] );
            ReverseRecursive( str , i , j );
      }

      return str;
}
Summary of ReverseRecursive()
ReverseRecursive() starts from the first index of the string and goes to the half length of the string. At each call it swap 2 elements of the string, i.e
In the first recursive call, it swaps first and the last element,
In the recursive second call, it swaps second and the second last element,
And so on…
ReverseRecursive() uses Swap() function to swap 2 elements of the string.
Summary of Swap()
Swap() takes 2 input parameters which are the pointers to the elements to be swapped.
First a temporary pointer temp is declared,
char temp;
which holds the data during swapping,
then the second element value2 is stored in temp
temp = *value2;
then the first element value1 is placed in the second element value2
*value2 = *value1;
and at the last the value of temp is assigned to value1
*value1 = temp;
Example (C++)
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

void Swap( char * value1 , char * value2 )
{
      char temp = *value2;
      *value2 = *value1;
      *value1 = temp;
}

char * ReverseRecursive( char str[] , int i , int j )
{
      if( i < strlen( str ) / 2 )
      {
            Swap( &str[i++] , &str[j--] );
            ReverseRecursive( str , i , j );
      }

      return str;
}

int main()
{
      char str[]="Saad Bin Saulat";
      cout << "Original string : " << str << endl;
      cout << "Reversed string : " << ReverseRecursive( str , 0 , strlen(str) - 1 ) << endl;

      _getche();
      return 0;
}
Output
Original string : Saad Bin Saulat
Reversed string : taluaS niB daaS

0 comments: