PUBLISHED ON: JANUARY 17, 2023
JavaScript Program to Check if the Numbers Have Same Last Digit
In this tutorial, we'll look at a JavaScript program that determines whether two numbers have the same last digit. The program will take two numbers as input and extract the last digit of each number using the modulus operator. The last digits of the two numbers will then be compared to see if they are the same. The program will then display a message indicating whether the numbers share the same last digit.
This program can be useful in a variety of applications, including credit card number validation, checking for duplicate entries in a database, and more. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Approach of the Program
The user takes the input of 2 integers. The main approach is to use the modulus operator.
- To extract the last digit of both numbers.
- Now we check for the similarity of both the last digits.
- If YES then it's the Same or else Different.
Program to Check if the Numbers Have Same Last Digit
// JavaScript Program to check whether the last digit of 2 numbers are the same
var x = prompt('Enter a first integer: ');
var y = prompt('Enter a second integer: ');
var res1 = x % 10;
var res2 = y % 10;
// compare the last digits
if(res1 == res2)
console.log("The numbers "+ x + " and " +y+ " have the same last digit.");
else
console.log("The numbers "+ x + " and " +y+ " do not have the same last digit.");
Enter a first integer: 2348
Enter a second integer: 3328
The numbers 2348 and 3328 have the same last digit.
Conclusion
Finally, we looked at a simple JavaScript program that checks if two numbers have the same last digit. The modulus operator is used by the program to extract the last digit of each number and then compares them to see if they are the same.
The program is easily adaptable to work with more than two numbers, or to perform additional actions based on the comparison result. Understanding how to check for the last digit of a number is an important concept in JavaScript programming, and this program is a good place to start.