• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Armstrong Number in Java | Print Armstrong Number between 1 to 1000

August 14, 2019 by javainterviewpoint Leave a Comment

An Armstrong Number is a number which is equal to the sum of its owns digits, each of them raised to the power of the total number of digits. In this article, Let’s write a program check whether the given number is Armstrong Number in Java.

What is an Armstrong Number?

A number is said to be an Armstrong Number, whenever it satisfies the below condition.

xyz = xn + yn + zn

n represents the number of digits.

Let’s understand with a pretty common example, 153 is an Armstrong number because it satisfies the condition sum of its digits raised to the power of the number of digits of that number should be equal to the actual number

153 = 13 + 53 + 33

Total number digit is 3 and hence the power is 3

13 = 1
53 = 125
33 = 27

1 + 125 + 27 = 153

Similarly 1634 is an Armstrong, 1634 => 14 + 64 + 34 + 44 => 1 + 1296 + 256 + 81  => 1634

Armstrong Number in Java

Let’s get into the coding

Program 1: Java Program to Check Armstrong Number using While Loop

package com.javainterviewpoint;

import java.util.Scanner;

public class ArmstrongNumber
{
    public static void main(String[] args)
    {
        Scanner scanner=new Scanner(System.in);
        System.out.println("Enter a number to check for Armstrong");
        
        int actualNumber = scanner.nextInt();
        int temp = actualNumber;
        int remainder = 0;
        int sum = 0;
        int n = 0;
        
        // Get the total number of digits
        while(temp != 0)
        {
            temp = temp / 10;
            n++;
        }
        temp = actualNumber;
        
        // Check for Armstrong Number
        while(temp != 0)
        {
            remainder = temp  % 10;
            sum = (int) (sum + Math.pow(remainder, n));
            temp = temp / 10;
        }
        
        if(actualNumber == sum)
            System.out.println(actualNumber + " is an Armstrong Number");
        else
            System.out.println(actualNumber + " is not an Armstrong Number");
    }
}
  • Get the number which needs to be checked from the user using the Scanner instance and store it in the variable actualNumber.
  • Store the input (actualNumber) in a temp variable, it is a necessary step to make a copy of the original number, because temp variable gets changed during the execution of the program and towards the end, we need the original input number for validation
  • Now we need to know the number of digits in the input number, in a while loop divide the temp value by 10 for each iteration increment the value of n, the loop continues till the value of temp is not equal to zero.
while(temp != 0)
{
      temp = temp / 10;
      n++;
}
  • Alternatively, we can get the number of digits in a simple way, just add an empty string and use the length() method to get the number of digits.

n = (actualNumber + “”).length();

  • Since the temp value will be zero now, we need to reassign it with the actualNumber
  • Now in a while loop, we need to extract the digits from right to left and raise them with the power of the number of digits. To get the individual numbers, divide the temp value by 10 using modulo operator [This gives us the remainder in the order of right to left]
  • Raise the remainder to the power of n using Math.pow() method, this method returns a double value we need to explicitly cast it to int so that we can add it to the existing sum.
  • In order to truncate the last digit, we need to divide the temp value by 10 and assign it back to temp. The while loop continues to execute until the value of temp is zero.
  • Finally, check whether the actualNumber and sum are equal, if so, then the number is Armstrong.

Output:

Enter a number to check for Armstrong
123
123 is not an Armstrong Number

Program 2: Armstrong Number in Java using For Loop

While loop checks for the Armstrong Numbers in the above program

Now let’s try to use For loop for doing the same validation

package com.javainterviewpoint;

import java.util.Scanner;

public class ArmstrongNumber
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number to check for Armstrong");
        int actualNumber = scanner.nextInt();
        int temp = actualNumber;
        int remainder = 0;
        int sum = 0;
        int n = 0;
        // Get the total number of digits
        n = (temp + "").length();
        
        // Check for Armstrong Number
        for(; temp > 0; temp /=10)
        {
            remainder = temp % 10;
            sum = (int) (sum + Math.pow(remainder, n));
        }
        
        if (actualNumber == sum)
            System.out.println(actualNumber + " is an Armstrong Number");
        else
            System.out.println(actualNumber + " is not an Armstrong Number");
    }
}

There are only two changes which we have made

  • Get the number of digits by simply appending the temp value with an empty string and call length() method on top of it get the total number of digits
  • Using for loop to perform the iteration, we have not assigned the initialization value, the loop will continue to execute until the value temp is greater than zero

Program 3: Java Program to Print Armstrong Number between 1 to 1000

In this Java program, we will take the start and end value from the user and print all the possible Armstrong numbers.

package com.javainterviewpoint;

import java.util.Scanner;

public class ArmstrongNumber
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the start value : ");
        int start = scanner.nextInt();
        System.out.println("Enter the end value : ");
        int end = scanner.nextInt();
        
        System.out.println("*** Printing the List of Armstrong Numbers ***");
        for(int i=start; i<=end; i++)
        {
            if(checkArmstrong(i))
                System.out.println(i);
        }
    }
    
    public static boolean checkArmstrong (int value)
    {
        int temp = value;
        int remainder = 0;
        int sum = 0;
        int n = 0;
        // Get the total number of digits
        n = (temp + "").length();
        
        // Check for Armstrong Number
        while (temp != 0)
        {
            remainder = temp % 10;
            sum = (int) (sum + Math.pow(remainder, n));
            temp = temp / 10;
        }
        
        if (value == sum)
            return true;
        else
            return false;
    }
}

Output:

Enter the start value : 
1
Enter the end value : 
1000
*** Printing the List of Armstrong Numbers ***
1
2
3
4
5
6
7
8
9
153
370
371
407

Although we have used the above code to print from 1 to 1000, the code works fine for any definitive ranges.

Happy Learning !!

Filed Under: Java, Java Interview, Java Program Tagged With: Armstrong Number, Armstrong Number in Java, Check Armstrong Number, Print Armstrong Number

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·