Java program to check armstrong number
In this section you will learn about the java program to check whether a number is Armstrong number or not?
In this section you will learn about the java program to check whether a number is Armstrong number or not?
Write a program to find out the Armstrong number using user input.: This java program checks if a number is Armstrong or not. Armstrong number is a number which is equal to sum of digits raise.
import java.util.Scanner;
class ArmstrongNumber
{
public static void main(String args[])
{
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
}
<b>Output 1:</b> Input a number to check if it is an Armstrong number 45781 45781 is not an Armstrong number. <b>Output 2:</b> Input a number to check if it is an Armstrong number 9926315 9926315 is an Armstrong number.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.