Page 1 of 1
PHP Exercise - Final sum of the digits of a number
Posted: 22 Nov 2014, 07:28
by Marius
Hi,
I have this php exercise:
- Calculate the final sum of the digits of a number, till get a number with one digit.
For example:
Code: Select all
$nr = 458;
// the code should calculate 4+5+8 = 17, then 1+7 = 8
// result is 8
Any idea, or example?
PHP Exercise - Final sum of the digits of a number
Posted: 22 Nov 2014, 07:35
by Admin
When you have to repeat multiple times the same operation on a variable, try to build the code based on a recursive function (which auto-calls itself).
Example:
Code: Select all
function getDigitControl($nr) {
// converts the $nr to string, get array with each digit, get the digits sum
// if $nr not lower than 10, auto-call this function with the last $nr
$nr = array_sum(str_split(strval($nr)));
return ($nr < 10) ? $nr : getDigitControl($nr);
}
$nr = 4512357;
echo getDigitControl($nr); // 9
PHP Exercise - Final sum of the digits of a number
Posted: 23 Nov 2014, 06:12
by Marius
Thank you.
Can you explain this line of code?
Code: Select all
return ($nr < 10) ? $nr : getDigitControl($nr);
PHP Exercise - Final sum of the digits of a number
Posted: 23 Nov 2014, 06:16
by MarPlo
The syntax:
is equivalent to:
Code: Select all
if(condition) { then A; }
else { then B; }
PHP Exercise - Final sum of the digits of a number
Posted: 07 Apr 2015, 06:41
by sandy
Another example with a recursive function:
Code: Select all
<?php
function add($nr) {
$nr = array_sum(str_split($nr));
if(strlen($nr) == 1) return $nr;
else return add($nr); //good example for recursive function
}
$nr = 852525488;
echo add($nr);
?>