### Recursion Problem

Hey everybody,
Not gonna lie. This is a homework help problem. I generally don't have difficulty with the homework problems for my C++ lab but part of my most recent one has just left me scratching my head. The assignment is to write a recursive function which takes any integer and prints that number in the correct order with '*' bookends as well as '*'s in between each digit of the number.

For example, if the function was given 7 as an input it would print *7*. If the input were 3457 it would print out *3*4*5*7*, etc. I'm not asking anyone to flatly give me the code that would yield this result but I really need a hint on this and I don't have the time to go to the departmental tutors at my college.

I was successful at getting *s in between each digit but not doing that in addition to having them surround the entire number. Here's the code I was able to come up with. When I run it with 7 as an input it just prints 7. When I run it with 1234 or another multiple digit number it prints 1*2*3*4...

 ``123456789`` ``````void printStarDigit(int x) { if(x < 10) { cout << x; return; } printStarDigit(x / 10); cout << '*'; printStarDigit(x % 10); }``````
Since you know x % 10 is going to be a single digit number, don't (recursively) invoke printStarDigit, but instead simply:
 ``12`` ``````//line 8 cout << (x % 10) ...``````
Then you know the cout on line 3 (in the recursive stop condition) is always printing the first digit (even in a one digit number), and the cout on line 8 will print all the digits after that. (You will still have the recursive call on line 6.)

Hopefully, I was clear enough to explain what I did to make it work, without giving you the code... But let me know if you still don't understand. Honestly, you are really close, so I wouldn't mind posting the code for you. (Too bad there's no spoiler system on here...)
Here's a hint. Change your base case from
 ``12345`` ``````if(x < 10) { cout << x; return; }``````

to
 ``12345`` ``````if(x == 0) { cout << '*'; return; }``````

In your other cases, print out a single digit and call the recursive function (not necessarily in that order... ;) )
Last edited on
Thanks Mathhead200, it was a huge help. Your answer really helped me understand how the function was actually working to begin with and I was able to edit the function to make it work as per the assignment.

Here it is:

 ``123456789`` ``````void printStarDigit(int x) { if(x < 10) { cout << '*' << x << '*'; return; } printStarDigit(x / 10); cout << x % 10 << '*'; } ``````
No problem. You ended up with exactly what I got too... :)
Topic archived. No new replies allowed.