
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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.
- Related Articles
- Swift Program to Calculate Cube Sum of First n Natural Numbers
- Java Program to calculate Sum of squares of first n natural numbers
- Sum of square-sums of first n natural numbers
- PHP program to find the sum of cubes of the first n natural numbers
- PHP program to find the sum of the 5th powers of first n natural numbers
- Difference between sum of the squares of and square of sum first n natural numbers.
- 8085 program to find the sum of first n natural numbers
- Java Program to cube sum of first n natural numbers
- Sum of first n natural numbers in C Program
- Swift Program to calculate the sum of first N even numbers
- Swift Program to calculate the sum of first N odd numbers
- Program to find sum of first n natural numbers in C++
- C Program for the cube sum of first n natural numbers?
- Python Program for cube sum of first n natural numbers
- C++ Program for cube sum of first n natural numbers?

Advertisements