Program to Reverse a Sentence Using Recursion in C++

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 reverseString function is called with str+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 reverseString(char *str) {
    if (*str == '\0') {
        return;
    } else {
        reverseString(str + 1);
        cout << *str;
    }
}

int main() {
    char originalString[] = "Welcome to Coding";
    cout << "Original String: " << originalString << endl;
    cout << "Reversed String: ";
    reverseString(originalString);
    return 0;
}


Output

Original String: Welcome to Coding
Reversed String: gnidnoC ot emocleW

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

  1. In the beginning, reverseString() accepts *str (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.
Program to Reverse a Sentence Using Recursion in C++