Program to Reverse a Sentence Using Recursion in C++
Written by
Program to Reverse a Sentence Using Recursion
Given: A string (terminated by null character), we have to reverse the string using recursion.
Algorithm
- Take a string and create a function to reverse it.
- If string not null then
reverseString
function is called withstr+1
value as argument. - 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.
- In the beginning, reverseString() accepts *str (a pointer that points to the start of the string).
- 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.
- It goes on till the string is null, the string are printed for back to front. We get the reversed string.