1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Unmash a string in C++ using recursion

  1. Oct 31, 2016 #1
    1. The problem statement, all variables and given/known data

    Part A: Have a user input a string. Then display this string smashed up as follows: display the first character in the string, then the last, then the second, then the second to last, then the third... So if the string is “abcdef”, it will display:
    afbecd (input “abcdef”)
    12345 --> 15243
    123456 --> 162534

    Part B: Now, unmash the above strings.
    i.e 162534 -->123456

    2. Relevant equations

    3. The attempt at a solution
    I got part A to work.
    Code (C):

    #include <iostream>
    using namespace std;
    void mash(string s);

    int main()
        string sequence;
        cout << "Enter a sequence: ";
        getline(cin, sequence);

    void mash(string s)
        int a = s.length();
        if (a == 0)
        if (a == 1)
        cout << s;
        cout << s[0];  
            cout << s[a - 1];  
            s = s.substr(1,a-2);
    but I have no clue how to approach part B. I guess I can try to print out the characters in the even position, say in the string 162534, thus I will get 123. Then I guess I can try to print out the odd position characters from the last one up to the first one, i.e, 456. Combining these two will get the original strings but I have no clue how to use recursion to solve part B.
    Last edited by a moderator: Oct 31, 2016
  2. jcsd
  3. Nov 1, 2016 #2


    User Avatar
    2017 Award

    Staff: Mentor

    You can use recursion in the sub-steps: one recursion for the even characters, one for the odd characters.
    Or unmash the string in the code with a recursive algorithm (2 characters at a time?), then print the whole string.
  4. Nov 3, 2016 #3


    User Avatar

    Staff: Mentor

    I'm looking forward to seeing the code you come up with to solve this. We can't help with improvements to your algorithm until you have first put in a good attempt by yourself.

    Recursive routines pack a lot of power into few lines, so it's worth investing time in getting them right.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted