Advertisement
Guest User

4 digits

a guest
Mar 17th, 2014
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1.  
  2. using System;
  3. using System.Text.RegularExpressions;
  4.  
  5.     class FourDigitNumber
  6.     {
  7.         static void Main()
  8.         {
  9.            while(true)
  10.            {
  11.             Console.Write("Enter a 4 digit number (can't start with 0) : ");
  12.             string str = Console.ReadLine();
  13.             Console.WriteLine();
  14.             int n;
  15.             int numb = int.Parse(str);
  16.             Regex regex = new Regex("^[1-9][0-9][0-9][0-9]*$");
  17.             if (int.TryParse(str, out n) && (regex.IsMatch(str)))
  18.             {
  19.                //Calculates the sum of the digits
  20.                 int sum = 0;
  21.                 while (n != 0)
  22.                 {
  23.                     int remainder;
  24.                     n = Math.DivRem(n, 10, out remainder);
  25.                     sum += remainder;
  26.                 }
  27.                 Console.WriteLine("Sum of digits : {0}", sum); // Prints the sum of the digits
  28.                 //Reverse the numbers
  29.                
  30.                 int reverse = 0;
  31.                 while (numb > 0)
  32.                 {
  33.                     int rem = numb % 10;
  34.                     reverse = (reverse * 10) + rem;
  35.                     numb = numb / 10;
  36.  
  37.                 }
  38.                 Console.WriteLine("Reversed : {0}", reverse);
  39.                 //Last digit at first position
  40.                 char[] str2 = str.ToCharArray();
  41.                 Console.WriteLine("Last digit in front : {3}{0}{1}{2}", str2[0], str2[1], str2[2], str2[3]);
  42.                 //Second and third digits exchanged
  43.                 Console.WriteLine("second and third digits exchanged : {0}{2}{1}{3}", str2[0], str2[1], str2[2], str2[3]);
  44.                 Console.WriteLine();
  45.             }
  46.             else
  47.             {
  48.                 Console.WriteLine("Not a 4 digit number : {0}", str);
  49.                 Console.WriteLine();
  50.             }
  51.         }
  52.     }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement