w3resource logo

:

php Programming Exercies

PHP Challenges: Add the digits of a positive integer repeatedly until the result has a single digit

PHP Challenges - 1: Exercise-12 with Solution

Write a PHP program to add the digits of a positive integer repeatedly until the result has a single digit.

Input : 48

For example given number is 59, the result will be 5.
Step 1: 5 + 9 = 14
Step 1: 1 + 4 = 5

Explanation :

PHP: Add the digits of a positive integer repeatedly until the result has single digit

Sample Solution :

PHP Code :

<?php
function add_digits($num)
{
      if ( $num > 0)
      {
      return ($num - 1) % 9 + 1;
      }
      else
      {
          return 0;
      }
}

print_r(add_digits(48)."\n");
print_r(add_digits(59)."\n");
?>

Sample Output:

3                                                           
5  

Flowchart:

PHP Flowchart: Add the digits of a positive integer repeatedly until the result has single digit

PHP Code Editor:

Improve this sample solution and post your code through Disqus