Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /* Write a program that takes as input a four-digit number in format abcd (e.g. 2011) and performs the following:
- * Calculates the sum of the digits (in our example 2+0+1+1 = 4).
- * Prints on the console the number in reversed order: dcba (in our example 1102).
- * Puts the last digit in the first position: dabc (in our example 1201).
- * Exchanges the second and the third digits: acbd (in our example 2101).
- * The number has always exactly 4 digits and cannot start with 0.
- * Examples:
- * n sum of digits reversed last digit in front second and third digits exchanged
- * 2011 4 1102 1201 2101
- * 3333 12 3333 3333 3333
- * 9876 30 6789 6987 9786 */
- class FourDigitNumber
- {
- static void Main()
- {
- int number = 0;
- Console.Write("Enter a integer between 1000 and 9999: ");
- if (int.TryParse(Console.ReadLine(), out number) && number >= 1000 && number <= 9999) //prevent to work whit an invalid data as "1d12" or 0-starting strings.
- {
- Console.Clear();
- //extracting the digits
- int firstDigit = number/1000;
- int secondDigit = ((number / 100) % 10);
- int thirdDigit = ((number / 10) % 10);
- int fourDigit = number % 10;
- //making varibles to pattern that will be printed
- int digitsSum = firstDigit + secondDigit + thirdDigit + fourDigit;
- string reversed = fourDigit.ToString() + thirdDigit.ToString() + secondDigit.ToString() + firstDigit.ToString();
- string lastInFront = fourDigit.ToString() + firstDigit.ToString() + secondDigit.ToString() + thirdDigit.ToString();
- string exchangedDigids = firstDigit.ToString() + thirdDigit.ToString() + secondDigit.ToString() + fourDigit.ToString();
- Console.WriteLine("n\tsum\treversed\tlast in front\texchanged digits"); //prints header
- Console.WriteLine("{0}\t{1}\t{2}\t\t{3}\t\t{4}", number, digitsSum, reversed, lastInFront, exchangedDigids);
- }
- else
- {
- Console.WriteLine("You have entered invalid data!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement