Java Program to print Armstrong numbers from 1 to n


February 18, 2022, Learn eTutorial
1801

Here we are explaining how to write a java program to display the Armstrong number from 1 to n.

What is Armstrong number?

An integer  number of n digits can be called as amstrong number, if it satisfy the following condition,

abcd...n=pow(a,n)+pow(b,n)+pow(c,n)+pow(d,n)+....

where a,b,c,d are the digits of the number .

How to implement the java program to display Armstrong numbers from 1 to n?

First, we have to declare the class AmstrongNum.Then declare the variables a,b,temp,n as integer.Create an object of the scanner class as sc and read the number from the user into the variable n. Assign temp=n.By using while loop assigns a=n.Now a contains the last digit of n.Assign n=n/10..Then find out the sum of the cubes of all digits as b=b+(a*a*a). After exiting from the loop, check if temp=b, if true then display the number b is Armstrong number. Else display the number is not Armstrong number using system.out.println().

 

ALGORITHM

STEP 1: Declare the class ArmstrongNumber with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variables a,b,temp,n.

STEP 4: Assign b=0.

STEP 5: Create an object of the scanner class as sc.

STEP 6: Read the number into the variable n.

STEP 7: By using for loop set i=1, check i<=n then do step 8.

STEP 8: Assign num=i,b=0.

STEP 8: By using a while loop check num>0, if true then do step 9.

STEP 9: Assign a=num,num=num/10,b=b+(a*a*a).

STEP 10: Check if i=b, if true then display the number i is amstrong number.

STEP 11: Increment i by one and repeat step 7.

Java Source Code

                                          import java.util.Scanner;
public class ArmstrongNumber {
 public static void main(String[] args) {
  int a,
  b = 0,
  temp,
  n,
  num;
  Scanner sc = new Scanner(System. in );

  System.out.println("Enter the value of n: ");
  n = sc.nextInt();

  for (int i = 1; i <= n; i++) {
   num = i;
   b = 0;
   while (num > 0) {
    a = num;
    num = num / 10;
    b = b + (a * a * a);
   }
   if (i == b) System.out.println(i);
  }
 }
}
                                      

OUTPUT

Enter the value of n: 1000
Armstrong Numbers from 1 to 1000
1
153
370
371
407