forked from atyant-yadav/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursion.cpp
More file actions
29 lines (24 loc) · 735 Bytes
/
Recursion.cpp
File metadata and controls
29 lines (24 loc) · 735 Bytes
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
/* Function to reverse a string using recursion */
#include <bits/stdc++.h>
#include <string>
using namespace std;
void stringReverse(string &line, int i = 0) {
int n = line.length();
if(i == n/2) { // if i reaches half of string length stop the process because once we reached half we know that
// string has been reversed(swapped).
return;
}
else {
swap(line[i], line[n - 1 - i]); // swap built-in function in bits/stdc++.h
stringReverse(line, i + 1);
}
}
int main()
{
string line;
cout<<"Enter string"<<endl;
getline(cin, line); // function to use when accepting a sentence as a input.
stringReverse(line);
cout<<line<<endl;
return 0;
}