w3resource
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:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to find the single element appears once in an array where every element appears twice except for one.
Next: Write a PHP program to reverse the digits of an integer.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming