- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP program to find the sum of cubes of the first n natural numbers
To find the sum of cubes of the first n natural numbers, the code is as follows −
Example
<?php function sum_of_cubes($val) { $init_sum = 0; for ($x = 1; $x <= $val; $x++) $init_sum += $x * $x * $x; return $init_sum; } print_r("The sum of cubes of first 8 natural numbers is "); echo sum_of_cubes(8); ?>
Output
The sum of cubes of first 8 natural numbers is 1296
A function named ‘sum_of_cubes’ is defined that initializes a sum to 0. Every natural number is multiplied by itself thrice (cube) and added to the initial sum. The limit is the value that is passed as a parameter to the function. The limit is defined outside the function and the function is called. Relevant output is displayed on the console.
Advertisements