Java Program To Check Armstrong Number or Not - #ArmstrongNumber / #java

0

Java Program to check Armstrong  Number or Not

 

#JavaArmstrongNumber

Example :- 153: 13 + 53 + 33 = 1 + 125+ 27 = 153

                154: 13 + 53 + 43 = 1 + 125+ 64  =  190 (Not an Armstrong Number)

 The following Java program print  the Armstrong numbers or not Armstrong number ......

Example 

 class armstrong{
    public static void main(String[] args){
        int num=153;
        int temp=num;
        int sum=0;
        int r=0;
        while(temp>0){
            r=temp%10;
            sum=sum+(r*r*r);
            temp=temp/10;
        }
        if(num==sum)
        {
            
            System.out.println("This is Armstrong Number...");

        }
        else
        {
            System.out.println("This is Not Armstrong Number...");
        }
    }

}

output 


This is Armstrong Number...

This Example Explanation:-

This Java code checks if a given number is an Armstrong number or not

An Armstrong number is a number that is equal to the sum of its own digits each raised
to the power of the number of digits.

Let's go through the code step by step:

1. int num = 153;: The variable num is assigned the value 153. This is the number we want
to check if it is an Armstrong number.

2.int temp = num;: The variable temp is initialized with the same value as num. We use temp to
perform calculations without modifying the original value of num.

3.int sum = 0;: The variable sum is initialized to 0. It will store the sum of each digit raised
to the power of the number of digits.

4.int r = 0;: The variable r is used to store the remainder when dividing temp by 10 (i.e., the
last digit of temp).

5.while (temp > 0) { ... }: This is a while loop that continues as long as temp is greater than 0.
The loop processes each digit of the number.

6. Inside the loop: a. r = temp % 10;: Get the last digit of temp by taking the remainder when dividing by 10.
b. sum = sum + (r * r * r);: Add the cube of the last digit to the sum. c. temp = temp / 10;: Remove the last digit from temp by integer division
(i.e., removing the last digit).

7.After the loop, sum will hold the sum of each digit raised to thepower of the number of digits.

8.if(num == sum) { ... }: Check if num is equal to sum. If they are equal,
the number is an Armstrong number,and the code inside the if block will be
executed.

9.Inside the if block, the program prints "this is armstrong number..." using System.out.println().

10.If num is not equal to sum, the code inside the else block will be executed, and the program
prints"this is not armstrong number..." using System.out.println().

If they are equal, the number is an " This is Armstrong Number...", and if not, it
"This is not Armstrong Number..."


Related Post  





Post a Comment

0Comments
Post a Comment (0)