Friday, August 28, 2015

Sum of odd natural number in PHP

/*
 *
 * sum of odd natural number
 * */
$x = 3;
$result = 0;
while($x){
  $result =$result + (2 * $x--)-1;
}
echo $result;

/*
 *
 * sum of odd natural number in another way
 * */
$n = 4;
$sum = 0;
$i = 1;
while($n--){
   $sum += $i;
   $i = $i + 2;
}
echo $sum;

No comments:

Post a Comment

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }