We should compose a java program to check whether the given number is armstrong number or not.
Armstrong Number in Java: A positive number is called armstrong number on the off chance that it is equivalent to the entirety of blocks of its digits for instance 0, 1, 153, 370, 371, 407 and so on.
How about we endeavour to comprehend why 153 is an Armstrong number.
153 = (1*1*1)+(5*5*5)+(3*3*3)
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153
How about we attempt to comprehend why 371 is an Armstrong number.
371 = (3*3*3)+(7*7*7)+(1*1*1)
where:
(3*3*3)=27
(7*7*7)=343
(1*1*1)=1
So:
27+343+1=371
Let's see the java program to check Armstrong Number.
class ArmstrongExample{
public static void main(String[] args) {
int c=0,a,temp;
int n=153;//It is the number to check armstrong
temp=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(temp==c)
System.out.println("armstrong number");
else
System.out.println("Not armstrong number");
}
}
Java Program to Check Armstrong Number
Here we will compose a java program that checks whether the given number is Armstrong number or not. We will see the two variety of a similar program. In the primary program we will allot the number in the program itself and in second program client would include the number and the program will check whether the info number is Armstrong or not.
Before we experience the program, lets see what is an Armstrong number. A number is called Armstrong number if the accompanying condition remains constant for that number:xy..z=xn+xn+......zn where n denotes the number of digits in the number For example this is a 3 digit Armstrong number
370=33+73+03
=27+343+0
=370
Example 1: Program to check whether the given number is Armstrong number
public class JavaExample {
public static void main(String[] args) {
int num = 370, number, temp, total = 0;
number = num;
while (number != 0)
{
temp = number % 10;
total = total + temp*temp*temp;
number /= 10;
}
if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
70 is an Armstrong number
In the above program we have used while loop, However you can also use for loop. To use for loop replace the while loop part of the program with this code:
for( ;number!=0;number /= 10){
temp = number % 10;
total = total + temp*temp*temp;
}
Example 2: Program to check whether the input number is Armstrong or not
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
int num, number, temp, total = 0;
System.out.println("Ënter 3 Digit Number");
Scanner scanner = new Scanner(System.in);
num = scanner.nextInt();
scanner.close();
number = num;
for( ;number!=0;number /= 10)
{
temp = number % 10;
total = total + temp*temp*temp;
}
if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
0 comments:
Post a Comment