Here we are write a program to find sum of digits of a given number, for the sum of digits we have to add all the digits of given number.
1. First you have to take the number.
2. Then divide the taken number by 10.
3. Store the remainder into a variable.
4. Final step repeat the process until remainder is 0.
Given program shows the sum of digits of 987654321.
1. Creating Three(3) PHP Variables. $num, $sum, $rem.
Variable $num will be store given numbers.
Variable $sum will be store total sum of digits.
Variable $rem will be store remainder of the number.
2. Then here we are using for loop for logical part, withing for loop we also use a php function strlen() to find length of numbers. ;enght of number we are checking with variable $i that was initialize by 0.
<?php $num = 987654321; $sum = 0; $rem = 0; for ($i =0; $i<=strlen($num);$i++) { $rem=$num%10; $sum = $sum + $rem; $num=$num/10; } echo "Sum of digits $num is $sum"; ?>
<form method="post"> <input type="text" name="number" placeholder="Enter number" /> <input type="submit" value="Submit" /> </form> <?php if(isset($_POST['number'])) { $onum = $_POST['number']; $num = $_POST['number']; $sum = 0; $rem = 0; for ($i =0; $i<=strlen($num);$i++) { $rem=$num%10; $sum = $sum + $rem; $num=$num/10; } echo "Sum of digits $onum is $sum"; } ?>
My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.