1. Introduction
An Armstrong number (also known as a plenary number, narcissistic number, or pluperfect number) in a given number base b is a number that is the sum of its own digits each raised to the power of the number of digits in its base b representation. For example, in base 10, the number 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. In this tutorial, we will write a Java program to display all Armstrong numbers within a specific range.
2. Program Steps
1. Declare a class named ArmstrongNumbers.
2. Inside this class, define the main method.
3. Inside the main method, declare the start and end of the range between which we want to find the Armstrong numbers.
4. Create a loop to iterate through all numbers in the specified range.
5. For each number, calculate the sum of its digits each raised to the power of the number of digits, and check whether it equals the original number.
6. If it does, print the number as it is an Armstrong number.
3. Code Program
public class ArmstrongNumbers { // Step 1: Declare a class named ArmstrongNumbers
// Method to check whether a number is an Armstrong number or not
static boolean isArmstrong(int num) {
int originalNumber, remainder, result = 0, n = 0;
originalNumber = num;
for (; originalNumber != 0; originalNumber /= 10, ++n);
originalNumber = num;
for (; originalNumber != 0; originalNumber /= 10) {
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
}
return result == num;
}
public static void main(String[] args) { // Step 2: Define the main method
int low = 1, high = 10000; // Step 3: Declare the start and end of the range
// Step 4: Create a loop to iterate through all numbers in the specified range
for (int number = low; number <= high; ++number) {
// Step 5: For each number, check whether it is an Armstrong number
if (isArmstrong(number))
// Step 6: If it is an Armstrong number, print the number
System.out.print(number + " ");
}
}
}
Output:
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474
4. Step By Step Explanation
– Step 1: A class named ArmstrongNumbers is declared.
– Step 2: The main method is defined inside the ArmstrongNumbers class.
– Step 3: We declare the start and end of the range between which we want to find the Armstrong numbers.
– Step 4: A for loop is used to iterate through all numbers in the specified range.
– Step 5: For each number in the loop, we check whether it is an Armstrong number using the isArmstrong method.
– Step 6: If the number is an Armstrong number, it gets printed to the console.
– The isArmstrong method calculates the sum of the digits of the number each raised to the power of the number of digits and checks whether it equals the original number.