Java Program – Armstrong number or not

This program is very useful for Fresher Java Programmer who is searching for a Job in Software Industry. Also, teachers can use this for school and college Lab program.

Here is the script (armstrong.java):

import java.io.*;
import java.util.Scanner;
public class armstrong {
    
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int num = 0, sum = 0, rem = 0, temp;
        num = sc.nextInt();
        temp = num;
        while(temp != 0){
            rem  = temp % 10;
            sum  = sum + (rem * rem * rem);
            temp = temp / 10;
        }
        if(num == sum){
            System.out.println("Armstrong Number");    
        }else{
            System.out.println("Not an Armstrong Number");
        }
        
    }
    
}

The logic of the program is very simple,

1. First store the entered number in a temp variable
2. In a while loop check till the temp number is not equal to 0 (zero)
3. If the temp is not 0 (zero) then find the reminder using % (modulus operator)
4. After finding the reminder multiple it three times and add it to the variable sum
5. Now find the quotient of the temp
6. Finally check the value of sum and num, if both the numbers are same then it is an “Armstrong Number”

To check this program use these Armstrong numbers:  371, 407 

You can download the Java Class here:

download

 

Leave a Comment

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

Scroll to Top