PHP Program to check whether the number Armstrong or Not


February 15, 2024, Learn eTutorial
2581

What is an Armstrong Number?

In this basic PHP program, we need to know what is meant by an Armstrong number. Armstrong number is a number in which the sum of the power raised to total digits in the number of each digit will be equal to the number itself. To know more about Armstrong numbers we have an interesting blog on The basics of Armstrong numbers

3 digit Armstrong number

A 3 digit number will be an Armstrong number if the sum of cubes of each digit will be equal to the number itself.

For example, let us take the number 153 and to check that number is an Armstrong number or not,

  • we need to take the cube of 1, 5, and 3
  • add those cubes together
  • and check if the result is equal to 153 or not ?
  • If it's 153, it's Armstrong's number. Else not
  • Here 1+125+27 =153, so it is an Armstrong number.

How to check whether a 3 digit number is an Armstrong number or Not in PHP?

In PHP to check whether a number is Armstrong or Not first, we have to read the input from the user and assign it to a variable. Then we have to split the digits of the number using the mod(%) operator by 10 and find the cube of each digit and add the results into a variable. After that, we have to compare the obtained result and the entered value if both values are equal then we can sort out that the entered number is an Armstrong number. Else if the entered number is not equal to the obtained result then the number won't be an Armstrong number.

ALGORITHM

Step 1: Accept the value from the user into the variable num

Step 2: Assign the value 0 into the variable total

Step 3: Perform the following sub-step until the condition 'x != 0' becomes false

            (i) Assign the computed result of 'x % 10' into the variable rem

            (ii) Assign the computed result of 'total + rem * rem * rem' into the variable total

            (iii) Assign the computed result of 'x / 10' into the variable x

Step 4: Check the condition 'num == total' if it is true then print 'Yes num is an Armstrong number' otherwise print 'No num is not an Armstrong number' using echo

PHP Source Code

                                          <?php
$num = readline("Enter the number: ");
$total = 0;
$x = $num;
while ($x != 0) {
    $rem = $x % 10;
    $total = $total + $rem * $rem * $rem;
    $x = $x / 10;
}
if ($num == $total) {
    echo "Yes $num is an Armstrong number";
} else {
    echo "No $num is not an armstrong number";
}
?>
                                      

OUTPUT

Enter the number: 407
Yes 407 is an Armstrong number