In this tutorial you will learn about the C++ program to Reverse a Sentence Using Recursion and its application with practical example.
C++ program to Reverse a Sentence Using Recursion
In this tutorial, we will learn to create a C++ program that will C++ Program to Reverse a Sentence Using Recursion in C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Usage of Conditional statements in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
What is Recursion? Reverse a Sentence Using it?
The recursion means a function or program that repeats itself until the condition is satisfied. The recursion repeats the program execution in a controlled format. Today we will reverse a sentence using the recursion.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking the input statement from the user. 3. Send that statement to the function. 4. Passing those variable to if conditional. 5. Printing the result words. |
Reverse a Sentence Using Recursion
In this program of recursion, we will take the input sentence from the user and store it in the string variable. Then will find the length of that string and at last, we will reverse that string using a recursion program.
With the help of the below, code we will Reverse a Sentence Using Recursion.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
/* C++ program to Reverse a Sentence Using Recursion */ #include <iostream> using namespace std; // declaring the user defined function for reversing the string from the user void reverse(const string& a); //body of the main function of the program int main() { //declaring the variable required to hold the string value from the user string str; //taking the input sentence from the user for hte reversing of string cout << " Please enter a string " << endl; getline(cin, str); // calling the user defined function toreverse the sentence reverse(str); return 0; } // definition of the user defined function for the reversing void reverse(const string& str) { // store the size of the string size_t numOfChars = str.size(); if(numOfChars == 1) { cout << str << endl; } else { cout << str[numOfChars - 1]; // function recursion reverse(str.substr(0, numOfChars - 1)); } } |
Output:-
In the above program, we have first initialized the required variable.
- str = string type variable that will hold the value of the input sentence.
Input strings from the user for program.
Reverse printing function for the sentence.
Main Function of the program.