Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text.RegularExpressions;
- class FourDigitNumber
- {
- static void Main()
- {
- while(true)
- {
- Console.Write("Enter a 4 digit number (can't start with 0) : ");
- string str = Console.ReadLine();
- Console.WriteLine();
- int n;
- int numb = int.Parse(str);
- Regex regex = new Regex("^[1-9][0-9][0-9][0-9]*$");
- if (int.TryParse(str, out n) && (regex.IsMatch(str)))
- {
- //Calculates the sum of the digits
- int sum = 0;
- while (n != 0)
- {
- int remainder;
- n = Math.DivRem(n, 10, out remainder);
- sum += remainder;
- }
- Console.WriteLine("Sum of digits : {0}", sum); // Prints the sum of the digits
- //Reverse the numbers
- int reverse = 0;
- while (numb > 0)
- {
- int rem = numb % 10;
- reverse = (reverse * 10) + rem;
- numb = numb / 10;
- }
- Console.WriteLine("Reversed : {0}", reverse);
- //Last digit at first position
- char[] str2 = str.ToCharArray();
- Console.WriteLine("Last digit in front : {3}{0}{1}{2}", str2[0], str2[1], str2[2], str2[3]);
- //Second and third digits exchanged
- Console.WriteLine("second and third digits exchanged : {0}{2}{1}{3}", str2[0], str2[1], str2[2], str2[3]);
- Console.WriteLine();
- }
- else
- {
- Console.WriteLine("Not a 4 digit number : {0}", str);
- Console.WriteLine();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement