Armstrong Number In Java Trick 2024
What Is an Armstrong Number?
A number is said to be an Armstrong number if it is equal to the sum of cubes of its digits.
For example:- If the input number is 153, the sum of the cubes of
it's digits (1+125+27=153) is the same as the number itself i.e.
153.
The first few Armstrong numbers between 0 to 999 are 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407.
In this tutorial first, we will write the Armstrong Number in Java Algorithm, then we will write Armstrong Number Java Program.
Armstrong Number in Java Algorithm:-
Step 1: Initialize a number (n).
Step 2: Make a copy of (n).
Step 3: Extract the last digits (extract) of the
number.
Step 4: Find the Sum of Cube (sumofcube) of each digit.
Step 5: Repeat steps 3 and 4 until the input number becomes 0.
Step 6: If the Sum of Cube (sumofcube) are equal to the number entered, then the number is an Armstrong else not.
For example:-
153: 13 + 53 + 33
= 1 + 125+ 27
= 153
The number 153 is an Armstrong number because the sum of cubes of each digit represent the number itself.
In this post, I will write a simple java program to check whether the number input by the user is an armstrong number or not.
Basically, the logic I have implemented in this program is pretty simple.
I will ask the user to enter a number then, pick each digit (Starting from the last digit) of the given number and find the cube of that digit.
Repeat this process till the first digit, then add all the cubes of each digit. Finally, I will check if the sum of cubes is equal to number or not.
Checkout:- Neon Number In Java - Solved Program
Checkout:- Spy Number In Java - Solved Program
Checkout:-
Print Two Dimensional Array Java
Checkout:- Java Program to Add Two Matrices
Checkout:- Java Program to Subtract The Two Matrices
Checkout:- Mirror Image of Matrix ISC 2013 Practical Java
Checkout:-
Sort Matrix in Ascending Order Java
Checkout:- Sorting Rows of Matrix in Descending Order Java
Checkout:-
Niven Or Harshad Number In Java
Armstrong Number In Java using While Loop
import java.util.*;
class Armstrong_Number
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int n,copyofn,sumofcubes=0,extract;
System.out.println("Enter any number");
n=sc.nextInt(); //Input Number (Ex. n=153)
copyofn=n; //Store copy of n
while(n!=0)
{
extract=n%10; //Extracts Last Digits(Ex. 153%10=3)
sumofcubes=sumofcubes + (extract*extract*extract); //Find sum of cubes of digits
n=n/10; //Reduces Number(Ex. 153/10= 15)
}
if(sumofcubes==copyofn)
{
System.out.println("It is an Armstrong Number");
}
else
{
System.out.println("Not an Armstrong Number");
}
}
}
----------
OUTPUT:-
----------
Enter any Number
153
It is an Armstrong Number
-------------------------
0 Comments
Just write down your question to get the answer...