Horje
Sum of First N Natural Number in PHP

Given a number N, the task is to find the sum of the first N natural numbers in PHP.

Examples:

Input: N = 5
Output: 15
Explanation: We will Add the Numbers till N
i.e. 1 + 2 + 3 + 4 + 5 = 15
Input: N = 10
Output: 55

There are different methods to find the sum of first N natural numbers, these are:

Using for Loop

We will iterate a loop from 1 to N and add all elements to get the sum of first N natural numbers.

Example:

PHP

<?php
  
$N = 5;
$sum = 0;
  
for ($i = 1; $i <= $N; $i++) 
    $sum = $sum + $i;
      
echo "Sum of first " . $N
    " Natural Numbers : " . $sum;
  
?>

Output

Sum of first 5 Natural Numbers : 15

Using Mathematical Formulae

The mathematical formula to find the sum of first N natural number is N * (N + 1) / 2.

Example:

PHP

<?php
  
$N = 5;
  
$sum = $N * ($N + 1) / 2;
  
echo "Sum of first " . $N
    " Natural Numbers : " . $sum;
  
?>

Output

Sum of first 5 Natural Numbers : 15



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Software Development Plan | Definition, Objective, and Steps Software Development Plan | Definition, Objective, and Steps
Software Development Outsourcing Companies - Introduction, Importance, and List Software Development Outsourcing Companies - Introduction, Importance, and List
CSS Overview Tool in Microsoft Edge Browser CSS Overview Tool in Microsoft Edge Browser
New Features of Microsoft Edge Developer Tools New Features of Microsoft Edge Developer Tools
Memory Tab in Google Chrome Browser Memory Tab in Google Chrome Browser

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11