PHP Program to find Average of N Numbers
You are Here:
Using for loop
In the following example, we will find the average of numbers between 1 and 10 using for loop.
Example
PHP Compiler
<?php
$start = 1;
$end = 10;
$total = 0;
$count = ($end - $start) + 1;
$average = 0;
echo "Average of numbers between $start and $end: <br>";
for($start=$start; $start<=$end; $start++)
$total += $start;
echo "<br> Total = $total";
echo "<br> Count = $count";
$average = $total / $count;
echo "<br> Average is $average";
?>
Output
Average of numbers between 1 and 10:
Total = 55
Count = 10
Average is 5.5
Using while loop
In the following example, we will find the average of numbers between 1 and 10 using while loop.
Example
PHP Compiler
<?php
$start = 1;
$end = 10;
$total = 0;
$count = ($end - $start) + 1;
$average = 0;
echo "Average of numbers between $start and $end: <br>";
while($start <= $end)
{
$total += $start;
$start++;
}
echo "<br> Total = $total";
echo "<br> Count = $count";
$average = $total / $count;
echo "<br> Average is $average";
?>
Output
Average of numbers between 1 and 10:
Total = 55
Count = 10
Average is 5.5
Using do while loop
In the following example, we will find the average of numbers between 1 and 10 using do while loop.
Example
PHP Compiler
<?php
$start = 1;
$end = 10;
$total = 0;
$count = ($end - $start) + 1;
$average = 0;
echo "Average of numbers between $start and $end: <br>";
do{
$total += $start;
$start++;
}while($start <= $end);
echo "<br> Total = $total";
echo "<br> Count = $count";
$average = $total / $count;
echo "<br> Average is $average";
?>
Output
Average of numbers between 1 and 10:
Total = 55
Count = 10
Average is 5.5
Reminder
Hi Developers, we almost covered 90% of String functions and Interview Question on PHP with examples for quick and easy learning.
We are working to cover every Single Concept in PHP.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.