settingsAccountsettings
Menusettings

Q: Play with Four-Digit Number in C#

+3 votes

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:

four digit number in c#

asked in C# category by user ak47seo
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

Interesting task indeed! Here is my solution - the explanation is in the comments:

using System;

class Program
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());//the user inputs 4 digits number

        int firstNumber = (n / 1000) % 10;//divide by 1000 >> then module dividing by 10 to get the 1st number of the 4th digit number
        int secondNumber = (n / 100) % 10;//divide by 100 >> then module dividing by 10 to get the 2nd number of the 4th digit number
        int thirdNumber = (n / 10) % 10;//divide by 10 >> then module dividing by 10 to get the 3rd number of the 4th digit number
        int fourthNumber = (n % 10);//Module dividing by 10 to get the 4th number of the 4th digit number

        //Console.WriteLine("{0},{1},{2},{3}",firstNumber, secondNumber, thirdNumber, fourthNumber);//Check whether it works!

        Console.WriteLine("The sum of the digits is: {0}", firstNumber + secondNumber + thirdNumber + fourthNumber);
        Console.WriteLine("Reversed order: {0}{1}{2}{3}", fourthNumber, thirdNumber, secondNumber, firstNumber);
        Console.WriteLine("Last digit upfront: {0}{1}{2}{3}", fourthNumber, firstNumber, secondNumber, thirdNumber);
        Console.WriteLine("Exchanges the second and the third digits: {0}{1}{2}{3}", firstNumber, thirdNumber, secondNumber, fourthNumber);
    }
}
answered by user hues
selected by user golearnweb
...