Deitel C++ How To Program 9th Edition Chapter 7 Exercise 7.31

17 Jul 2024 - Syed Muhammad Shahrukh Hussain

Write a program which reverses a string using recursion.

Terminal

hgfedcba

Solution

#include <iostream>
#include <string>

using namespace std;

void stringReverse(string &str, int start);

int main() {
  string str =  "abcdefgh";
  stringReverse(str, 0);
  cout << endl;
  return 0;
}

void stringReverse(string &str, int start) {
  if ( str[start] !=  '\0' ) {
    stringReverse(str, start + 1);
    cout << str [start];
  }
}

Sources