An Armstrong number (also known as a narcissistic number) is a number that equals the sum of its own digits each raised to the power of the number of digits. For instance, 153 is an Armstrong number because (1^3 + 5^3 + 3^3 = 153). Exploring Armstrong numbers between two intervals can be a common task in introductory Java programming courses, providing a great way to learn about loops, conditionals, and functions.
In this article, you will learn how to create a Java program that displays Armstrong numbers between two intervals. The explanations, followed by code examples, will guide you through writing a function that checks for Armstrong numbers, and then using that function to find and display them within a specified range.
Utilize Java's mathematical operations to break down the number into digits.
Calculate the sum of the digits each raised to the power of the total number of digits.
Return true
if the sum equals the original number, otherwise return false
.
public static boolean isArmstrong(int number) {
int 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);
}
return (result == number);
}
In this code:
for
loop.isArmstrong()
to check each number, and print it if it is an Armstrong number.Create a Scanner object to capture user input.
Promote good user interaction by providing clear prompts.
Iterate through the desired range, and use the function to check for Armstrong numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int low, high;
System.out.print("Enter the lower bound: ");
low = scanner.nextInt();
System.out.print("Enter the upper bound: ");
high = scanner.nextInt();
System.out.println("Armstrong numbers between " + low + " and " + high + " are: ");
for (int i = low; i <= high; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
}
}
Scanner
class is used for capturing user input.for
loop runs through each number in the user-specified range.isArmstrong()
method is called to check each number.By following the steps outlined above, you now have a Java program capable of identifying and displaying Armstrong numbers within a specified interval. Such tasks enhance understanding of functions, loops, and basic number manipulation in Java. Implementing these concepts in practical applications like finding Armstrong numbers provides valuable hands-on experience in programming basics. This knowledge applies across various scenarios, making your programming journey easier and more efficient.