Programming Problems: Digits of an Integer

Programming Problems is a recurring segment where I explain and explore assignments covered in introductory programming for C#.  If I can explain it, then I know it.  

3.28 (Digits of an Integer) Write an app that inputs one number consisting of five digits from the user, separates the number into its individual digits and displays the digits separated from one another by three spaces each. For example, if the user types in the number 42339, the app should display
Assume that the user enters the correct number of digits. What happens when you execute the app and type a number with more than five digits? What happens when you execute the app and type a number with fewer than five digits? [Hint: It’s possible to do this exercise with the tech- niques you learned in this chapter. You’ll need to use both division and remainder operations to “pick off” each digit.]
— http://www.deitel.com/Books/C/VisualC2012HowtoProgram/tabid/3645/Default.aspx

This weeks question is a simple one.  The fundamental lesson of this question and assignment is to determine if one is able to mathematically isolate digits in an entered string for comparison.  This skill will become handy in the future.  To mathematically split each digit in an input:

Split == number to be isolated

1s =     Split mod 10;  
10s =    (Split / 10) mod 10;
100s =   (Split / 100) mod 10;
1000s =  (Split / 1000) mod 10;
10000s = (Split / 10000) mod 10;

This can be repeated again and again for any placeholder digit that is required.  Once it is known how to isolate each digit, laying out how to program the problem becomes considerably easier.  Let's start by analyzing what the question is looking for:

  • Prompt user to input a five (5) digit integer

  • Separates the input into its individual digits

  • Display the separated digits with three spaces

These simple requirements can be solved many ways, here is one simple solution:

using System;

public class SpaceFiveDigits
{
    static void Main(string[] args)
    {
        int Digit1; 
        int Digit2;
        int Digit3;
        int Digit4;
        int Digit5;
        int ToSplit;

        Console.Write("Please enter a five (5) digit number: "); 
        ToSplit = Convert.ToInt32(Console.ReadLine());


        Digit5 = ToSplit % 10;  
        Digit4 = (ToSplit / 10) % 10;
        Digit3 = (ToSplit / 100) % 10;
        Digit2 = (ToSplit / 1000) % 10;
        Digit1 = (ToSplit / 10000) % 10;

        Console.WriteLine("{0} {1} {2} {3} {4} ", Digit1, Digit2, Digit3, Digit4, Digit5); //prints single digit integers with spaces
        Console.ReadLine();

    } // end main
} // end class

Hope this helps explain how to create a simple application in C# using basic math.  Good luck, and keep working hard. 

Transmit: FTP Client for OS X

Transmit: FTP Client for OS X

Shellshocked? Me too, try 1Password