Algorithm
-
Input:
- Take an integer input (let's call it
num) from the user.
- Take an integer input (let's call it
-
Initialization:
- Initialize three variables:
originalNumto store the original value ofnum,resultto store the result of the Armstrong number check, andnto store the number of digits innum.
- Initialize three variables:
-
Count Digits:
- Calculate the number of digits in
numand store it inn. You can use a loop to repeatedly dividenumby 10 until it becomes zero, incrementingnin each iteration.
- Calculate the number of digits in
-
Calculate Armstrong Number:
- Initialize
resultto 0. - Iterate through each digit of
originalNumusing a loop.- Calculate the
digitby taking the remainder when dividingoriginalNumby 10. - Update
resultby adding thedigitraised to the power ofn. - Divide
originalNumby 10 to move to the next digit.
- Calculate the
- After the loop, check if
resultis equal to the original numbernum. If true, thennumis an Armstrong number.
- Initialize
-
Output:
- Display the result, indicating whether the number is an Armstrong number or not.
Code Examples
#1 Code Example- Check Armstrong Number for 3 digit number
Code -
Java Programming
public class Armstrong {
public static void main(String[] args) {
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
Copy The Code &
Try With Live Editor
Output
371 is an Armstrong number.
#2 Code Example- Check Armstrong number for n digits
Code -
Java Programming
public class Armstrong {
public static void main(String[] args) {
int number = 1634, originalNumber, remainder, result = 0, n = 0;
originalNumber = number;
for (;originalNumber != 0; originalNumber /= 10, ++n);
originalNumber = number;
for (;originalNumber != 0; originalNumber /= 10)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
Copy The Code &
Try With Live Editor
Output
1634 is an Armstrong number.
Demonstration
Java Programing Example to Check Armstrong Number-DevsEnv