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
#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.