Java program to print all armstrong numbers between given range code example

Example 1: Java program to print armstrong number from 1 to 1000

public class ArmstrongBetween1To1000
{
   public static void main(String[] args)
   {
      int number, n, total = 0;
      System.out.println("Armstrong number between 1 to 1000: ");
      for(int a = 1; a <= 1000; a++)
      {
         number = a;
         while(number > 0)
         {
            n = number % 10;
            total = total + (n * n * n);
            number = number / 10;
         }
         if(total == a)
         {
            System.out.print(a + " ");
         }
         total = 0;
      }
   }
}

Example 2: 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 ArmstrongNumbersGivenRange 
{
   public static void main(String[] args) 
   {
      int number, startNumber, endNumber, a, rem, n, count = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter starting number range: ");
      startNumber = sc.nextInt();
      System.out.println("Please enter ending number range: ");
      endNumber = sc.nextInt();
      for(a = startNumber + 1; a < endNumber; a++)
      {
         n = a;
         number = 0;
         while(n != 0)
         {
            rem = n % 10;
            number = number + rem * rem * rem;
            n = n / 10;
         }
         if(a == number)
         {
            if(count == 0)
            {
               System.out.println("Armstrong numbers between given range " + startNumber + " and " + endNumber + ": ");
            }
            System.out.print(a + "  ");
            count++;
         }
      }
      // if there is no Armstrong number found between range
      if(count == 0)
      {
         System.out.println("Sorry!! There's no armstrong number between given range " + startNumber + " and " + endNumber);
      }
      sc.close();
   }
}

Tags:

Java Example