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?
RUN CODE SNIPPETSource Code
#include <iostream>
#include <stdio.h>
using namespace std;
void reverse(char *str)
{
if(*str == '\0')
return;
else
{
reverse(str+1);
cout<<*str;
}
}
int main()
{
char str[30];
cin.getline (str, 30);
cout<<"Original String: "<<str<<endl;
cout<<"Reversed String: ";
reverse(str);
return 0;
}Input
Hello World
Output
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.
- Declare the void function and assign the reverse function to the variable str which is declared as a string value.
- Declare an if statement with the condition
(*str == '\0') and insert a return statement, in the body of the else statement insert the mathematical functionreverse(str+1)and an output function with cout statement. - Declare the int main followed by declaring the str variable as a character with char with the size of the variable in square brackets [ ].
- Use cin.getline to store a string value with spaces, that is a sentence specifying in brackets the variable and the size.
- 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.