w3resource logo


php exercises

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
Output : 3

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");
?>

Output :

3                                                           
5  

Flowchart:

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

PHP Code Editor:

<?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");
?>

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables