C++ Program to Reverse a Sentence Using Recursion

In this post, you will learn how to Reverse a Sentence Using Recursion using C++.

This lesson will teach you how to Reverse a Sentence Using Recursion, mathematical operators and decision making statement using the C++ Language. Let’s look at the below source code.

How to Reverse a Sentence Using Recursion?


Source Code

#include <iostream>
#include <stdio.h>
using namespace std;
void reverse(char *str) 
   if(*str == '\0')
int main() 
   char str[30];
   cin.getline (str, 30);
   cout<<"Original String: "<<str<<endl;
   cout<<"Reversed String: ";
   return 0;


Hello World


Original String: Hello World
Reversed String: dlroW olleH

The statements #include<iostream>, using namespace std are the main factors that support the function of the source code. The void keyword is used when the function does not have a return value.  The #include <stdio.h> enables the use of additional output functions in the code.

Now we can look into the working and layout of the code’s function.

  1. Declare the void function and assign the reverse function to the variable str which is declared as a string value.
  2. Declare an if statement with the condition (*str == '\0')
     and insert a return statement, in the body of the else statement insert the mathematical function reverse(str+1)and an output function with cout statement.
  3. Declare the int main followed by declaring the str variable as a character with char with the size of the variable in square brackets [ ].
  4. Use cin.getline to store a string value with spaces, that is a sentence specifying in brackets the variable and the size.
  5. Use the cout functions to display the output statements, followed by a reverse function of the variable and include the return statement.

Note: The ‘ << endl ‘ in the code is used to end the current line, to understand how the function works exclude it from the code, move it around and work with it.