Q:

Sum of Digits in Php

belongs to collection: PHP Programs

0

To find sum of digits of a number just add all the digits.

For example,

 

14597 = 1 + 4 + 5 + 9 + 7  

14597 = 26  

Logic:

  • Take the number.
  • Divide the number by 10.
  • Add the remainder to a variable.
  • Repeat the process until remainder is 0.

All Answers

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

Example:

Given program shows the sum of digits of 14597.

<?php  
$num = 14597;  
$sum=0; $rem=0;  
  for ($i =0; $i<=strlen($num);$i++)  
 {  
  $rem=$num%10;  
   $sum = $sum + $rem;  
   $num=$num/10;  
  }  
 echo "Sum of digits 14597 is $sum";  
 ?>  

Output:

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

total answers (1)

Even Odd Program in Php... >>