I'm running Microsoft Visual Studio 2010 Professional on a Windows 7 laptop and trying to learn C#. I'm working on recursion and want to prompt the user to enter a specific word into a console application and then use a recusive method to print each character of the user-supplied word on a separate line by itslef. What is the best way to accomplish this task?
Software/Hardware used:
ASKED:
January 28, 2011 5:07 PM
UPDATED:
January 31, 2011 7:36 PM
I’m pretty sure recursion is not the best way, but that is how you want to do it.
As this is for learning purposes, you might want to try different ways (if there are
), and then post the code of the different methods you have tried, and ask for recomendations about the best method.
Assuming this isn’t a homework question, there are two obvious recursive ways to do this (in pseudo-code, not C++):
function leftprint ( s : string ) : string { print left( s , 1); if len(s) > 1 then leftprint ( substring (s , 2, len (s)) ); }or
function rightprint ( s : string ) : string { if len(s) > 1 then rightprint ( left ( s , len (s) - 1) ); print right ( s, 1 ); }The first is the simplest conceptually – just peel off and print the leftmost character, then call yourself with the remaining string after that.
The second is more interesting – it is “remembering” characters from the right during the descent, and printing them on the way back up.
Both produce the same result, but it is useful to understand the difference and when to use which style (hint – in this case, the first style is more efficient – “why” is left as an exercise for the student
).