PHP Program to find the sum of n natural number


April 6, 2022, Learn eTutorial
2635

How to calculate the sum of n natural numbers using PHP?

In this program, we are going to find the sum of the n natural number. For that we first have to read the n number into the variable num. after that we have to assign that to the variable n and also assign the value 0 to the variable sum. Then we have to perform the while loop until the condition 'n >= 0' becomes false and in the block of the loop, we have to assign the computed value of 'sum + n' to the variable n and decrement the value of the variable n. After the completion of the loop, we have to print the value of the variable sum as the sum of the n natural number. For example, if the entered number is 5 then the result will be 1+2+3+4+5 = 15

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

                                          <?php
$num = readline("Enter the n number: ");
$n = $num;
$sum = 0;
while ($n >= 0) {
    $sum = $sum + $n;
    $n--;
}
echo "Sum of $num number is: $sum";
?>
                                      

OUTPUT

Enter the number: 10
Sum of 10 number is: 55