RUN


Program to Reverse a Sentence Using Recursion

Given: A string (terminated by null character), we have to reverse the string using recursion.

Algorithm

  1. Take a string and create a function to reverse it.
  2. If string not null then reverse function is called with string+1 value as argument.
  3. Until the end of the string is reached this goes on and when null is encountered then our string is printed back to front.

Code

#include <iostream>

using namespace std;

void rev_str(char *string) 

{

   if(*string == '\0')

       return;

    else 

    {

       rev_str(string+1);

       cout<<*string;

    }

}

int main() 

{

 char string[] = "Welcome to Coding";

    cout<<"Original String: "<<string<<endl;

    cout<<"Reversed String: ";

   rev_str(string);

    return 0;

}

In the above program, the function rev_str() is a recursive function that reverses a string.

  1. In the beginning, rev_str() accepts *string (a pointer that points to the start of the string).
  2. If the string is null, then the function returns else the function recursively calls itself with the value string+1 which means next element in the string.
  3. It goes on till the string is null, the string are printed for back to front. We get the reversed string.

 

Report Error/ Suggestion

Related Posts:




CopyRight © 2020

CopyRight © 2020