Computer >> Computer tutorials >  >> Programming >> PHP

PHP program to find the average of the first n natural numbers that are even


To find the average of the first n natural numbers that are even, the code is as follows −

Example

<?php
function even_nums_avg($val)
{
   return $val + 1;
}
$val = 11;
print_r("The average of the first n natural numbers that are even is ");
echo(even_nums_avg($val));
?>

Output

The average of the first n natural numbers that are even is 12

A function named ‘even_nums_avg’ is defined that adds up all the numbers up to a given limit, and divides it by total numbers of values. This is the average of the first few natural numbers. A value is defined, and the function is called by passing this value, which is actually the limit up to which the average of numbers needs to be found. Relevant message is displayed on the console.