Reverse string with recursion

    0

    1

    Giovanny Gongora

    Codiga's C++ Recipes

    Take a sentence and reverse it using recursion.

    #include <iostream>
    
    using namespace std;
    // function prototype
    void reverse(const string& a);
    // function definition
    void reverse(const string& str) {
      // store the size of the string
      size_t numOfChars = str.size();
      if(numOfChars == 1) {
        cout << str << endl;
      }
      else {
        cout << str[numOfChars - 1];
        // function recursion
        reverse(str.substr(0, numOfChars - 1));
      }
    }
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.