settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: How to find the last digit of a number "n" and print it in C#

+4 votes

In C# I need to write a program that prints in the console application the last digit of a particular number "n".

For example:

n

Result

21

1

139

9

4

4

 

asked in C# category by user hues

1 Answer

+1 vote
 
Best answer

Solution:

  1. Declare two variables (n and lastDigit).
  2. Read the user input from the console. (int.Parse(Console.ReadLine());).
  3. Find the last digit of the number by the formula: int lastDigit = n % (10); (Use modular division - the operator % in C#).
  4. Print the result on the console (Console.WriteLine(lastDigit));)

using System;

class LastDigit
{
    static void Main()
    {
        Console.WriteLine("Please write your number:");
        long n = long.Parse(Console.ReadLine());

        long lastDigit = n % (10);  //or int or double - whatever numeral data type suits you
        Console.WriteLine("The last digit of your number {0} is: {1}", n, lastDigit);
    }
}
answered by user mitko
selected by user golearnweb
...