Try a specific example: reverse the string "Hello".
This would give: "o" + reverse of "Hell" [sic] - 4 remaining letters
which is: "o" + "l" + reverse of "Hel" - 3 remaining letters
which is: "o" + "l" + "l" + reverse of "He" - 2 remaining letters
which is: "o" + "l" + "l" + "e" + reverse of "H" - 1 remaining letter
When it gets down to 1 remaining letter it doesn't need to reverse anything, just return that letter.
So, for a recursive function to reverse a string of N letters:
- if N is 1, just return the one-character string;
- otherwise, return a string formed from 'last letter of string' + reverse of substring with N-1 letters.
Since the recursion reduces N by 1 each time, it will work its way down to 1, then return back in the opposite order (as @eyenriques' example shows).
Check out the string methods (particularly substr() ) on this site.
Incidentally, if you have to use a void function, then the argument will have to be a reference (use an &s, not s in the argument list). Alternatively, use a string return type, rather than void.
A couple of other comments:
- I guess that your teacher has specified the form of the function so you don't have much option, but it wouldn't actually be vital to pass integer N: this could be deduced automatically from the length of the string;
- it seems a rather inefficient way of reversing a string!