C++ program to Reverse a Sentence Using Recursion


A string is a one dimensional character array that is terminated by a null character. The reverse of a string is the same string in opposite order. For example.

Original String: Apple is red
Reversed String: der si elppA

A program that reverses a sentence in the form of a string using recursion is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
void reverse(char *str) {
   if(*str == '\0')
   return;
   else {
      reverse(str+1);
      cout<<*str;
   }
}
int main() {
   char str[] = "C++ is fun";
   cout<<"Original String: "<<str<<endl;
   cout<<"Reversed String: ";
   reverse(str);
   return 0;
}

Output

Original String: C++ is fun
Reversed String: nuf si ++C

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

Initially reverse() accepts *str which is a pointer that points to the start of the string. If the value is null, then the function returns. If not, then the function recursively calls itself with the value str+1 i.e the next element in the string. Eventually, when str is null, the values of str are printed for back to front. So, the reversed string is printed. This is shown by the following code snippet.

if(*str == '\0')
   return;
   else {
      reverse(str+1);
      cout<<*str;
   }

In the main() function, the string is initialized. Also, the original string and the reversed string are displayed. This is shown as follows −

char str[] = "C++ is fun";
cout<<"Original String: "<<str<<endl;
cout<<"Reversed String: ";
reverse(str);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 24-Jun-2020

769 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements