Sum of Digits of a Number PHP Program using While loop
Sum of digits of a number PHP program using while loop.
In this article, you will learn how to make the sum of digits of a number PHP program using while loop which can be 2 or more digits value.
Example
The concept of the sum of digits is:
You should have knowledge of the following topics in PHP programming to understand this program:
- PHP
echo
andprint
statement - PHP
while
loop
Source Code
<?php
$x = 1569;
$sum = 0;
$m = NULL;
echo "The sum of ", $x, " digits is = ";
// It will calculate the sum of each digit of the input number
while ($x > 0) {
$m = $x % 10;
$m = intval ($m);
$sum = $sum + $m;
$x = $x / 10;
$x = intval ($x);
}
// It will print the final output;
echo $sum;
?>
Output
The sum of 1569 digits is = 21
Explanation
In this given program, we have taken an input variable $x
with its assigned value 1569
. Then we applied the while loop on this number to iterate over this number and to get each digit from this number.
On each iteration, It received the digit and assigned it to the $m
variable, and added the value of $m to the $sum
variable.
After the whole process, the $sum variable is returned the sum of each digit is 21
, It's the final output of the program.
- INPUT: 1569 => 1+5+6+9 = 21