Reversing a string makes use of recursion. - C++ Data Type

C++ examples for Data Type:char array

Description

Reversing a string makes use of recursion.

Demo Code

#include <iostream>
#include <cstring>
using namespace std;

void revstr_recursive(char *str, int start, int end) {
  if (start < end)
    revstr_recursive(str, start + 1, end - 1);
  else//from  w w w.  j a  v  a 2s  . c om
    return;
  char t = str[start];
  str[start] = str[end];
  str[end] = t;
}
// Reverse a string in place by using recursion.
void revstr_r(char *str) {
  revstr_recursive(str, 0, strlen(str) - 1);
}
int main() {
  char str[] = "abcdefghijklmnopqrstuvwxyz";
  cout << "Original string: " << str << endl;
  revstr_r(str);
  cout << "Reversed string: " << str << endl;
  return 0;
}

Result


Related Tutorials