Print armstrong numbers in the given range

Java Program to Print Armstrong numbers between the given range

To print Armstrong numbers between the given range in java, we first need to understand what is an Armstrong number. An Armstrong number is the number that is equal to the sum of the cubes of the single individual digits of the number. For example, we want to check if 153 is an Armstrong number or not. We will take the sum of cubes of 1, 5 and 3 which is 1+125+27. The sum is equal to 153. As a result, we conclude that 153 is an Armstrong number. The program in java to print an Armstrong number is below.

To check if a number is Armstrong or not, we follow the following algorithm:

  • We take the integer value and assign them a value.
  • Then we split the integer value.
  • We find the cube value of each integer value and split them.
  • We save the single outputs and add them together.
  • The integer value is an Armstrong number if the sum is equal to the initial input value.
  • The integer value is not an Armstrong number if the sum is not equal to the initial input value.

Armstrong number between the given ranges

import java.util.Scanner;
public class DeveloperHelps
{
public static void main(String args[])
{
int n, n1, n2, i, rem, temp, count=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the starting number of the range :  ");
n1 = scan.nextInt();
System.out.print("Enter the ending number of the range :  ");
n2 = scan.nextInt();		       
for(i=n1+1; i<n2; i++) {
temp = i;
n = 0;
while(temp != 0)
{
rem = temp%10;
n = n + rem*rem*rem;
temp = temp/10;
}
if(i == n)
{            	
if(count == 0)
{
System.out.print("Armstrong Numbers between the given range are: \n");
}
System.out.print(i + "  ");
count++;
}
}
if(count == 0){
}
System.out.print("Armstrong Number is not Found between the given range");
}
}

The output of the following program will be:

Enter the starting number of the range:  90
Enter the starting number of the range:  501
Armstrong Numbers between the given range are: 153 370 371 407

The user enters the range in which he wants to find the Armstrong numbers in the above program. As the user enters the starting and ending range, a ‘for’ loop is used which finds all the Armstrong numbers. We use our logic for checking the numbers. If we find a number that lies in the Armstrong number category, the value is printed in the output. Otherwise, a message is displayed that Armstrong Number is not found between the given range.

Thanks for the reading post. I hope you like and understand the post. If you have any doubts regarding this post please comment below.

Leave a comment

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