VOOZH about

URL: https://www.geeksforgeeks.org/php/sum-of-first-n-natural-number-in-php/

⇱ Sum of First N Natural Number in PHP - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of First N Natural Number in PHP

Last Updated : 16 Nov, 2023

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

👁 Image

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:


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:


Output
Sum of first 5 Natural Numbers : 15
Comment
Article Tags: