- Related Questions & Answers
- Sum of square-sums of first n natural numbers
- Java Program to calculate Sum of squares of first n natural numbers
- PHP program to find the sum of cubes of the first n natural numbers
- Difference between sum of the squares of and square of sum first n natural numbers.
- PHP program to find the sum of the 5th powers of first n natural numbers
- Sum of first n natural numbers in C Program
- 8085 program to find the sum of first n natural numbers
- Java Program to cube sum of first n natural numbers
- Sum of square of first n odd numbers
- C Program for the cube sum of first n natural numbers?
- Sum of sum of first n natural numbers in C++
- C++ Program for Sum of squares of first n natural numbers?
- Sum of squares of first n natural numbers in C Program?
- Python Program for Sum of squares of first n natural numbers
- C++ Program to Calculate Sum of Natural Numbers

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

<?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); ?>

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.

Advertisements