# Armstrong Number In Java

In this tutorial, we will learn about Armstrong number in Java. What is Armstrong number? Check whether a number is Armstrong number or not.

## Armstrong Number

It is a number which equals to the sum of cubes of its individual digits.

For example-153 is an Armstrong number because

Cubes of 1 = 1

Cubes of 5 = 125

Cubes of 3 = 27

Sum of Cubes = 1 + 125 + 27 = 153

2nd example- 370 is an Armstrong number because-

Cubes of 3 = 27

Cubes of 7 = 343

Cubes of 0 = 0

Sum of Cubes = 27 + 343 + 0 = 370

### Algorithm of Armstrong Number

1. Take Integer variable i
2. Assign a value to this integer i
3. Split all digits of  i
4. Calculate cube of each digits if i
5. Calculate sum of cubes of all digits
6. Save output of sum into SUM variable
7. If SUM is equal to the i, print Armstrong Number
8. If SUM is no equal to the i, print not Armstrong Number

Let’s see the java program to check Armstrong Number or not.

public class ArmstrongNo {
public static void main(String args[]) {
int number = 370;
int temp, rem, sum = 0;
System.out.println("Enter a number to be verified:");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
temp = number;
while(temp != 0) {
rem = temp % 10;
sum = sum + (rem * rem * rem);
temp = temp / 10;
}
if(sum == number)
System.out.println(number +"is an Armstrong number.");
else
System.out.println(number +" is not an Armstrong number.");
}
}

Output:
Enter a number to be verified:
370
370 is an Armstrong number.

## Java Program to Print Armstrong number in java from 0 to 999

package com.automationtesting;
public class ArmstrongNo {
public static void main(String[] args) {
int temp, digit, digitCubSum;

for (int inputArmstrongNo = 0; inputArmstrongNo < 1000; inputArmstrongNo++) {
temp = inputArmstrongNo;
digitCubSum = 0;
while (temp != 0) {

digit = temp % 10;

//sum of cubes of each digit is equal to the temp no. itself
digitCubSum = digitCubSum + digit * digit * digit;

temp /= 10;

}

//check given temp and digitCubSum is equal to or not
if (digitCubSum == inputArmstrongNo)
System.out.println(inputArmstrongNo + " is an Armstrong No.");

}

}

}

Output

0 is an Armstrong No.

1 is an Armstrong No.

153 is an Armstrong No.

370 is an Armstrong No.

371 is an Armstrong No.

407 is an Armstrong No.

## Armstrong Number in java using recursion

### Recursion – When a method is called itself continuously. This method is called recursive method.

import java.util.Scanner;
class ArmstrongRecursionNo
{
int x;
int findArmstrongno(int n,int b)
{
if(n!=0)
{
x=n%10;
b=b+(x*x*x);
n/=10 ;
return findArmstrongno(n,b);
}
return b;
}
public static void main(String[] arg)
{
ArmstrongRecursionNo A=new ArmstrongRecursionNo();
int arm;
System.out.println("Armstrong number between 1 to 1000");
for(int y=1;y<500;y++)
{
arm=A.findArmstrongno(num,0);
if(arm==num)
System.out.println(num);
}
}
}

Output:

Armstrong numbers between 1 to 1000

1

153

370

371

407