C++ Program to Find Last Digit of a Number

In this post, we will learn how to find the last digit of a number using C++ Programming language.

We will calculate the last digit of a number using (%) Modulus operator.

We will be using the following approaches to find the last digit of a number.

  1. Using Standard Method
  2. Using Function

So, without further ado, let’s begin this tutorial.

C++ Program to Find Last Digit of a Number

// C++ Program to Find Last Digit of a Number
#include <iostream>
using namespace std;

int main(){
    int num, digit;
    
    // Asking for input
    cout << "Enter a number: ";
    cin >> num;
    
    // Finding last digit
    digit = num % 10;
    
    // Displaying output
    cout << "Last digit of " << num << " is: " << digit << endl;
    return 0;
}

Output

Enter a number: 527
Last digit of 527 is: 7

How Does This Program Work ?

    int num, digit;

In this program, we have declared two integer data type variables named num and digit.

    // Asking for input
    cout << "Enter a number: ";
    cin >> num;

Now, the user is asked to enter a number.

    // Finding last digit
    digit = num % 10;

We compute the last digit of the entered number using (%) Modulus operator. Modulus (%) returns the remainder, which is usually the last digit of any number.

For example, if the user enters a number 815, then 815 % 10 = 5 which is the last digit. Similarly, if the user enters 640, then 640 % 10 = 0, which is the last digit of the number.

    // Displaying output
    cout << "Last digit of " << num << " is: " << digit << endl;

Then, we print the result on the screen using the cout statement.

C++ Program to Find Last Digit of a Number Using Function

// C++ Program to Find Last Digit of a Number Using Function
#include <iostream>
using namespace std;

int lastDigit(int n){
    return (n % 10);
}

int main(){
    int num, digit;
    
    // Asking for input
    cout << "Enter a number: ";
    cin >> num;
    
    // Calling out function 
    digit = lastDigit(num);
    
    // Displaying output
    cout << "Last Digit of " << num << " is: " << digit << endl;
    return 0;
}

Output

Enter a number: 1024
Last Digit of 1024 is: 4

Conclusion

I hope after going through this post, you understand how to find the last digit of a number using C++ Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to assist you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *