Algorithm
-
Input:
- Take an input number from the user.
-
Initialization:
- Initialize variables to store the sum of the cubes of digits and a temporary variable to store the original number.
-
Extract Digits:
- Create a loop to extract each digit of the number.
- Inside the loop, extract the last digit using the modulo operator (
%
) and update the original number by removing the last digit.
-
Cube and Sum:
- Cube each extracted digit and add it to the sum.
-
Check Armstrong Condition:
- After processing all digits, compare the sum with the original number.
- If they are equal, the number is an Armstrong number; otherwise, it is not.
-
Output:
- Display the result to the user.
Code Examples
#1 Code Example- Check Armstrong Number of Three Digits
Code -
Javascript Programming
// program to check an Armstrong number of three digits
let sum = 0;
const number = prompt('Enter a three-digit positive integer: ');
// create a temporary variable
let temp = number;
while (temp > 0) {
// finding the one's digit
let remainder = temp % 10;
sum += remainder * remainder * remainder;
// removing last digit from the number
temp = parseInt(temp / 10); // convert float into integer
}
// check the condition
if (sum == number) {
console.log(`${number} is an Armstrong number`);
}
else {
console.log(`${number} is not an Armstrong number.`);
}
Copy The Code &
Try With Live Editor
Output
Enter a three-digit positive integer: 153
153 is an Armstrong number.
153 is an Armstrong number.
#2 Code Example- Check Armstrong Number of n Digits
Code -
Javascript Programming
// program to check an Armstrong number of n digits
// take an input
const number = prompt("Enter a positive integer");
const numberOfDigits = number.length;
let sum = 0;
// create a temporary variable
let temp = number;
while (temp > 0) {
let remainder = temp % 10;
sum += remainder ** numberOfDigits;
// removing last digit from the number
temp = parseInt(temp / 10); // convert float into integer
}
if (sum == number) {
console.log(`${number} is an Armstrong number`);
}
else {
console.log(`${number} is not an Armstrong number.`);
}
Copy The Code &
Try With Live Editor
Output
Enter a positive integer: 92727
92727 is an Armstrong number
92727 is an Armstrong number
Demonstration
JavaScript Programing Example to Check Armstrong Number-DevsEnv