One of the books I'm currently reading to learn C# asked me to write a method that takes an integer between 1 and 99999 and displays each number in that integer in a sequence, separating each digit by 2 spaces.
For example: the int 87564
would be written to the console as 8 7 5 6 4
.
This is simple enough to do using the input as a string, converting it to a char array, or looping over the string with a foreach
and printing out a formatted string for each character.
For fun though and mostly to challenge myself, I like to work out the problems as they are intended for someone just learning the concepts for the first time. The chapter was about methods and briefly introduced recursion. It's clearly the author's intent that you solve this using division and modulus operations to pick off each digit and then write them out.
So there really were limited options in terms of solving this with the material you have learned to this point in the book. You could pick off each digit and store it as it's own variable, then later write them out in order since you know the range of integers.
I decided to make the method more useful by really allowing any non-negative integer and my approach involved recursion. I'm not really experienced using recursion so I'd like to get some feedback on my implementation to see what I could have done better.
public class Program
{
static void Main()
{
// Get User Input From Console
// Validate and parse as int input
DisplayDigits(input);
}
static void DisplayDigits(int value)
{
if (value < 10)
{
Console.Write("{0} ", value);
return;
}
DisplayDigits(value / 10);
Console.Write("{0} ", value % 10);
}
}
Obviously, this is not meant to be production level code, I'm solving the problem in the textbook and then throwing the code away.
It appears to be working for all non-negative numbers I've tried. I even wrote an overload that takes a ulong
and passed it UInt64.MaxValue
and it printed everything fine. I can't help but feel like maybe it could be better in some way. Any criticism, suggestions, links to more reading material would be appreciated.
DisplayDigits
isstatic
because it's called fromstatic void Main()
?). \$\endgroup\$