Sum of Cubes of Odd Natural Numbers in PHP



To find the sum of cubes of natural numbers that are odd, the code is as follows −

Example

 Live Demo

<?php
function sum_of_cubes_even($val)
{
   $init_sum = 0;
   for ($i = 0; $i < $val; $i++)
      if ($i % 2 != 0)
         $init_sum += (2 * $i) * (2 * $i) * (2 * $i);
   return $init_sum;
}
print_r("The sum of cubes of first 8 natural numbers that are even is ");
echo sum_of_cubes_even(8);
?>

Output

The sum of cubes of first 8 natural numbers that are even is 3968

A function named ‘sum_of_cubes_even’ is defined that takes a limit on the natural number up to which the cube of every number needs to be found and each on them need to be added up. A ‘for’ loop is iterated over, and every number is cubed and added to an initial sum that was initially 0. The function is called by passing a number that is the limit as parameter. Relevant message is displayed on the console.

Updated on: 2020-07-02T07:01:25+05:30

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements