PHP Program to average of n numbers

What is meant by the average of n numbers?

To find the average of n numbers we first find the sum of n numbers and then divide the result by n. For example, if the numbers are 5, 7, 9 then, in this case, n will be 3, and to find the average we first have to add 5, 7, 9 which is 21 after that we have to divide 21 by which is 7.

How to find the average of n numbers in PHP?

To find the average of n numbers using PHP first of all we have to accept the limit of numbers(n) into the variable limit. Then we have to assign the value into the variable and perform the operations until the condition 'i <= limit'  becomes false and the first we have to accept the numbers into the variable num and then we have to add the value of the variable sum with the current value of the variable num. After the completion of the loop, we have to assign the value of the variable sum divide by the value of the variable limit into the variable average. And at last, we have to print the value of the variable average as the average of the numbers.

ALGORITHM

Step 1: Accept the limit of numbers from the user and assign it to the variable limit

Step 2: Assign the value 0 into the variable sum

Step 3: Assign the value 1 into the variable i and perform the sub-step until the condition 'i <= limit' becomes false and increment the value of the variable by 1 in every iteration

        (i) Accept the value into the variable num

        (ii) Assign the computed value of 'sum + num' into the variable sum

Step 4: Assign the computed value of 'sum/limit' into the variable average

Step 5: Print the value of the variable average as the average of the entered numbers

PHP Source Code

                                          <?php
$limit = readline("Enter the limit of numbers: ");
$sum = 0;
for ($i = 1; $i <= $limit; $i++) {
    $num = readline("Enter the number $i : ");
    $sum = $sum + $num;
}
$average = $sum / $limit;
echo "The average is $average";
?>

                                      

OUTPUT

Enter the limit of numbers: 5
Enter the number 1 : 75
Enter the number 2 : 84
Enter the number 3 : 6
Enter the number 4 : 49
Enter the number 5 : 10
The average is 44.8