PHP Program to find the sum of digits


April 16, 2022, Learn eTutorial
1362

What is meant by the sum of digits?

The sum of digits is meant by adding all the digits of the number. For example, if the entered number is 258 then to find sum of the digits will be 2 + 5 + 8 which will be 15.

How to find the sum of digits using PHP

In this program to find the sum of the digits first, we have to read the number into the variable and then we have to find the length of the number and assign it to a variable and perform the operations using for loop for each digits of the entered number. The operations to perform the are 'number % 10' to find the reminder, 'sum + remainder' to add every digit with each other 'number / 10' to remove the last digit of the number, and after the completion of the loop print the sum as the sum of the digits of the number.

ALGORITHM

Step 1: Accept the number from the user and assign the value to the variable number

Step 2: Assign the value of the variable number into the variable n

Step 3: Assign the value 0 into the variable s(to store the sum of digits) and r(to store the remainder)

Step 4: Find the length of the variable n using the built-in function strlen() and assign it to the variable len

Step 5: Assign the value 0 into the variable i and perform the following sub-steps until the condition 'i <= len' and increment the value of variable i in every iteration

        (i) Assign the computed value of 'n % 10' into the variable r

        (ii) Assign the computed value of 's + r' into the variable s

        (iii) Assign the computed value of 'n / 10' into the variable n

Step 6: Print the value of variable s as the sum of the number entered

PHP Source Code

                                          <?php
$number = readline("Enter the number: ");
$n = $number;
$s = 0;
$r = 0;
$len = strlen($n);
for ($i = 0; $i <= $len; $i++) {
    $r = $n % 10;
    $s = $s + $r;
    $n = $n / 10;
}
echo "Sum of digits $number is $s";
?>
                                      

OUTPUT

Enter the number: 673
Sum of digits 673 is 16