Q:

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

0

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 2: 1 + 4 = 5

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now