In this tutorial, we will write a Program to Reverse a String in C++ using recursion. Before beginning, you must be familiar with the following topics in C++.
Recursion refers to the process when a function calls itself inside that function directly or indirectly or in a cycle.
If you want to learn more about recursion in detail, click here. Although it is for C programming, the theory concept of recursion is the same for all programming languages.
C++ Program to Reverse a String using Recursion
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 | #include <iostream> using namespace std; void reverseFunc(char *str); //function prototype //main function int main() { char str[] = "This is simple2code.com"; cout << "Actual String: " << str << endl; cout << "\nReversed String: "; reverseFunc(str); return 0; } //recursion function void reverseFunc(char *str) { if (*str == '\0') //base condition { return; } else { reverseFunc(str + 1); cout << *str; } } |
Output:
Actual String: This is simple2code.com
Reversed String: moc.edoc2elpmis si sihT
You may go through the following program on a string.