In PHP, while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop than for loop.
PHP program to print all natural numbers from 1 to N (ALGORITHM)
Step 1: Accept the number from the user and insert it into the variable num
Step 2: Assign the value of variable num into the variable n and assign the value 0 into the variable sum
Step 3: Perform the following sub-steps until the condition ‘n >= 0’
(i) Assign the calculated value of ‘sum + n’ into the variable sum
(ii) Decrement the value of the variable n
Step 4: Print the value of the variable sum as the sum of n natural number
PHP Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <form action=""> <input type="text" name="num"> <input type="submit" value="Print"> </form> <div> <?php if(isset($_GET["num"])){ $num = $_GET["num"]; $n = $num; $sum = 0; while ($n >= 0) { $sum = $sum + $n; $n--; } echo "Sum of $num number is: $sum"; } ?> </div> |
Output: