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:
originalNum
to store the original value ofnum
,result
to store the result of the Armstrong number check, andn
to store the number of digits innum
.
- Initialize three variables:
-
Count Digits:
- Calculate the number of digits in
num
and store it inn
. You can use a loop to repeatedly dividenum
by 10 until it becomes zero, incrementingn
in each iteration.
- Calculate the number of digits in
-
Calculate Armstrong Number:
- Initialize
result
to 0. - Iterate through each digit of
originalNum
using a loop.- Calculate the
digit
by taking the remainder when dividingoriginalNum
by 10. - Update
result
by adding thedigit
raised to the power ofn
. - Divide
originalNum
by 10 to move to the next digit.
- Calculate the
- After the loop, check if
result
is equal to the original numbernum
. If true, thennum
is 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