JAVA PROGRAM
Write a program to display armstrong numbers within a range | Java Program |
Introduction
Armstrong numbers, also known as narcissistic numbers, are numbers that are equal to the sum of the cubes of their digits. For example, 153 is an Armstrong number because 1³ + 5³ + 3³ equals 153.
In this blog post, we'll explore how to create a Java program that identifies and displays Armstrong numbers within a user-defined range.
Code
import java.io.*;
import java.util.*;
public class arms {
public static void main(String args[]) throws IOException {
int n, n1, n2, i, rem, temp, count = 0;
DataInputStream s = new DataInputStream(System.in);
System.out.println("Enter the starting number:");
n1 = Integer.parseInt(s.readLine());
System.out.println("Enter the ending number:");
n2 = Integer.parseInt(s.readLine());
for (i = n1 + 1; i < n2; i++) {
temp = i;
n = 0;
while (temp != 0) {
rem = temp % 10;
n = n + rem * rem * rem;
temp = temp / 10;
}
if (i == n) {
if (count == 0) {
System.out.println("Armstrong numbers in the given range are:");
count++;
}
System.out.println(i + " ");
}
}
if (count == 0) {
System.out.println("No Armstrong numbers found in the given range!");
}
}
}
Output
Enter the starting number:
1
Enter the ending number:
500
armstrong numbers in the given range are:
153
370
371
407
Explanation
1. Input Handling:
The program starts by asking the user to input the starting and ending numbers of the range.
2. Iterating Through the Range:
It then iterates through the numbers within the given range (excluding the starting and ending numbers themselves).
3. Checking for Armstrong Numbers:
For each number, it checks if the sum of the cubes of its digits equals the number itself. This is done using a while loop that extracts each digit, cubes it, and accumulates the sum.
4. Displaying Results:
If a number matches the Armstrong condition, it is printed. If no Armstrong numbers are found, a message indicating this is displayed.
Conclusion
Armstrong numbers are a fascinating mathematical concept, and writing a Java program to find them within a range is a great exercise for practicing loops, conditionals, and user input handling. This simple program can be expanded or modified to work with numbers having more digits or different criteria for the Armstrong condition.
Post a Comment
0 Comments