Java Code to generate Armstrong Numbers between 2 Numbers

A number is called Armstrong Number if the  sum of all digit’s cube in a number is equal to the original number. For example : 153=1^3 + 5^3 + 3^3 = 1*1*1 + 5*5*5 + 3*3*3

The following code accepts two numbers from the key board and prints the Armstrong Numbers between the given two numbers.


package com.javaonline;

import java.util.Scanner;

class ArmstrongNumbers {

public static void main(String[] args) {

try {

	System.out.println("Enter Number 1");

	Scanner sc = new Scanner(System.in);

	int number1 = sc.nextInt();

	System.out.println("Enter Number 2");

	sc = new Scanner(System.in);

	int number2 = sc.nextInt();

	System.out.println("Armstrong Numbers between "+ number1 + " and " + number2);

	int n=0;

		for (int j=number1 ; j<=number2 ; j++)

		{

			int sum=0;

			int d=0;

			n=j;

			while (n>0)

			 {

				d= n%10;

				sum=sum+d*d*d;

				n=n/10;

				}

			      if (sum==j)

				{

				System.out.println(j +" ");

				}

			}

		}

		catch (Exception e)

		{

		System.out.println("Error");

		}

		}

}

Run the program and give the input number 1 & 1000.

Output :

armstrong numbers

You may also like

Leave a Reply