Table of Contents
Print the reverse of a string using recursion.
Example
a) Input string : Sachin
Output : nihcas
b) Input string : Code
Output : edoC
Time complexity : O(n)
Algorithm
Create Reverse function to reverse string recursively
In this function,
a. It takes string pointer (str) as input.
b. It calls itself (recursively) with next location to passes pointer (str+1).
c. Continue recursion till it reaches the end of the string.
d. After all functions accumulated in stack print char at passed pointer.
e. Return one after one.
Algorithm working
C++ Program
#include <bits/stdc++.h> using namespace std; //Recursive function to reverse a string void Reverse(char *str) { if(*str) { Reverse(str+1); cout<<*str; } } //Main function int main() { char string[] = "code"; cout<<"Input string: "; for (int i = 0; i < strlen(string); ++i) { cout<<string[i]; } cout<<"\nOutput string after reversing: "; Reverse(string); return 0; }