In this article, we will make a program to find an Armstrong Number Using JavaScript. Here, we will get a number from the user, and we will just find where given number is Armstrong or not. We will add the logic for this table in a function. We will use some HTML element to get the user’s input, but we can also use prompt instead of input field to make this program in JavaScript purely.
What is Armstrong Number?
Armstrong number is a number that is equal to the sum of cubes of its digits. For example, 0, 1, 153, 370, 371 and 407 are the Armstrong numbers. Let’s take 153 then 1**3 + 5**3 + 3**3 =1+125+27=153, here (**) is the power of a number.
Creating Program to Find Armstrong Number
So firstly, we will make an HTML markup as always. Then in this we have to add a script tag to write the JS code. You can also make a separate file for the JS and add the path in the HTML. In this HTML, we have added an input field to get the user’s input and a button, on which we have applied onclick event listener with a function call to get the result.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="number" id="num1">
<button onclick= res()>Result</button>
<script>
var result;
function res(){
var x = document.querySelector("input").value;
var temp = x;
var sum = 0;
while(temp>0){
var digit = temp%10;
sum += digit**3;
temp= parseInt(temp/10);
}
(x==sum)? document.write(`<h1>${x} is an armstrong number</h1>`)
: document.write(`<h1>${x} is not an armstrong number`)
}
</script>
</body>
</html>
Now, in this function, we have declared a variable x in which we have to fetch the value using document.querySelector("input").value
to get value from the input value. Then we have added another variable in which we will store the value for temporary basis to identify number property. Then we have added another variable to store sum with initial 0 value.
Now we have added a while loop, in which we are rotating this loop until temp gets empty. In this we have added a variable named digit in which we will store the remainder of temp. Like if we have 153 then 3 will be stored in the digit.
After that, we will multiply the digit 3 times and add it in the sum. Then we will update temp value by dividing it with 10. After all iterations will be done, then we will check the condition in which we will compare x with sum. If both are equal then we will print the message as a positive message, and if both aren’t equal then we will print a negative message.
If you want to make it in JS only, then you can remove input field and button. And you can use prompt() to get the user’s value.