Java Program to Print All Armstrong Numbers Between Given Range

You are currently viewing Java Program to Print All Armstrong Numbers Between Given Range

Java program to print all Armstrong numbers between given range

import java.util.Scanner;

public class GenerateArmstrongNumber
{
    public static void main(String args[])
    {
        int n, n1, n2, i, rem, temp, count=0;
        Scanner scan = new Scanner(System.in);
        
        /* enter the interval between which number is printed */
        
        System.out.print("Enter the Interval :\n");
		
        System.out.print("Enter Starting Number :  ");
        n1 = scan.nextInt();
        System.out.print("Enter Ending Number :  ");
        n2 = scan.nextInt();
		
        // read numbers one-by-one and generate armstrong.
        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)
            {
            	// print all the armstrong number between given interval.
                if(count == 0)
                {
                    System.out.print("Armstrong Numbers Between the Given Interval are : \n");
                }
                System.out.print(i + "  ");
                count++;
            }
        }
        // print if no number found.
        if(count == 0)
        {
            System.out.print("Armstrong Number not Found between the Given Interval.");
        }
    }
}

Output

First run:
Enter the Interval :
Enter Starting Number : 100
Enter Ending Number : 500
Armstrong Numbers Between the Given Interval are : 
153  370  371  407  

Second run:
Enter the Interval :
Enter Starting Number :  100
Enter Ending Number :  1500
Armstrong Numbers Between the Given Interval are : 
153  370  371  407  

Third run:
Enter the Interval :
Enter Starting Number :  1
Enter Ending Number :  150
Armstrong Number not Found between the Given Interval.

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply