C++ Program to Find the Unit Digit of a Number

unit digit

C++ program to find the unit digit of a number has been shown here. The unit digit of a number is also referred to as the last digit. In the decimal number system, we can determine the unit digit by dividing the number by 10 and obtaining the remainder.


Example:

1. The unit digit of 123 is 3 (123 % 10 = 3)

2. The unit digit of 4567 is 7 (4567 % 10 = 7)

3. The unit digit of 89125 is 5 (89125 % 10 = 5)


In C++ program, we can use modulus operator (%) to extract the unit digit.






1. Algorithm to Find the Unit Digit of a Number


1. Take a number n as input

2. Compute u = n mod 10

3. Declare u as the unit digit and exit program




2. Pseudocode to Find the Unit Digit of a Number


Input: A number $n$

Output: Unit digit of $n$

1. Procedure unitDigit($n$):

2. $u \leftarrow n \mod 10$

3. Return $u$

4. End Procedure





3. Time Complexity to Find the Unit Digit of a Number


Time Complexity: O(1)




4. C++ Program to Find the Unit Digit of a Number

Code has been copied
/***********************
   alphabetacoder.com
 C++ Program to find the 
 unit digit of a number
************************/
#include <iostream>

using namespace std;

int main() {
    // declare variables
    int n, u;

    //take input of the number
    cout << "Enter the number = ";
    cin >> n;

    // extract the unit digit
    u = n % 10;

    // display the result
    cout << "Unit digit of " << n << " is: " << u << endl;

    return 0;
}

Output


Enter the number = 1729

Unit digit of 1729 is: 9