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

PHP program to calculate the sum of square of first n natural numbers


To calculate the sum of square of first n natural numbers in PHP, the code is as follows −

Example

<?php
function sum_of_squares($limit)
{
   $ini_sum = 0;
   for ($i = 1; $i <= $limit; $i++)
      $ini_sum += ($limit * $limit);
   return $ini_sum;
}
$limit = 5;
print_r("The sum of square of first 5 natural numbers is ");
echo sum_of_squares ($limit);
?>

Output

The sum of square of first 5 natural numbers is 125

A function named ‘sum_of_squares’ is defined that takes the limit up to which square of natural number needs to be found. In this function, a sum value is initialized to 0. A ‘for’ loop is run over the elements ranging from 1 to the limit. Every time, to the ‘sum’ variable, square of the iterated value is added. When the control reaches the end, the value of sum is returned as the output. Outside the function, a limit value is specified and the function is called by passing the limit value to it.