Advertisement
milen8204

[C# Basics]Problem6.FourDigitNumber

Mar 17th, 2014
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.23 KB | None | 0 0
  1. using System;
  2. /* Write a program that takes as input a four-digit number in format abcd (e.g. 2011) and performs the following:
  3.  *  Calculates the sum of the digits (in our example 2+0+1+1 = 4).
  4.  *  Prints on the console the number in reversed order: dcba (in our example 1102).
  5.  *  Puts the last digit in the first position: dabc (in our example 1201).
  6.  *  Exchanges the second and the third digits: acbd (in our example 2101).
  7.  *  The number has always exactly 4 digits and cannot start with 0.
  8.  *  Examples:
  9.  *  n       sum of digits   reversed    last digit in front     second and third digits exchanged
  10.  *  2011    4               1102        1201                    2101
  11.  *  3333    12              3333        3333                    3333
  12.  *  9876    30              6789        6987                    9786 */
  13. class FourDigitNumber
  14. {
  15.     static void Main()
  16.     {
  17.         int number = 0;
  18.         Console.Write("Enter a integer between 1000 and 9999: ");
  19.  
  20.         if (int.TryParse(Console.ReadLine(), out number) && number >= 1000 && number <= 9999) //prevent to work whit an invalid data as "1d12" or 0-starting strings.
  21.         {
  22.             Console.Clear();
  23.             //extracting the digits
  24.             int firstDigit = number/1000;
  25.             int secondDigit = ((number / 100) % 10);
  26.             int thirdDigit = ((number / 10) % 10);            
  27.             int fourDigit = number % 10;
  28.            
  29.             //making varibles to pattern that will be printed
  30.             int digitsSum = firstDigit + secondDigit + thirdDigit + fourDigit;
  31.             string reversed = fourDigit.ToString() + thirdDigit.ToString() + secondDigit.ToString() + firstDigit.ToString();
  32.             string lastInFront = fourDigit.ToString() + firstDigit.ToString() + secondDigit.ToString() + thirdDigit.ToString();
  33.             string exchangedDigids = firstDigit.ToString() + thirdDigit.ToString() + secondDigit.ToString() + fourDigit.ToString();
  34.  
  35.             Console.WriteLine("n\tsum\treversed\tlast in front\texchanged digits"); //prints header
  36.             Console.WriteLine("{0}\t{1}\t{2}\t\t{3}\t\t{4}", number, digitsSum, reversed, lastInFront, exchangedDigids);
  37.         }
  38.         else
  39.         {
  40.             Console.WriteLine("You have entered invalid data!");
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement