Q:

Java program to print all Armstrong numbers between given range

belongs to collection: Java Basic Programs

0

Given a range of numbers and we have to print all Armstrong numbers between the range using Java program.

Example 1:

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

Example 2:

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print Armstrong numbers between a range in Java

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to find sum of all digits ... >>
<< Java program to generate permutation and combinati...