Sum of Natural Numbers in PHP

Sum of Natural Numbers in PHP

<?php
$n=5; // Initialises n to 10 for sum of natural no. up to 10
$sum=0;
for($i=1;$i<= $n; $i++)
{
$sum = $sum +$i; // This statement execution i will explain below
}
echo $sum;

?>

// First iteration, $sum=0 and $i=1 on the right side then left side $sum=1
// Second iteration, $sum=1 and $i=2 on the right side then left side $sum=3
//Third iteration  , $sum=3 and $i=3 on the right side then left side $sum=6
// Fourth iteration, $sum=6 and $i=4 on the right side then left side $sum=10
// Fourth iteration, $sum=10 and $i=5 on the right side then left side $sum=15
____________________________________
See the  video for output and program execution

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.