PHP (Core & Framework)

Write a program in PHP to find the sum of first 20 even numbers

sum-of-first-20-even-numbers

There are two methods for calculating sum of first n say 20 even numbers

First method – using For Loop :

You can calculate some of first n numbers using for loop, see the code below :

<?php 
   $n = 20; 
    $currEven = 2; 
    $sumEven = 0; 
  
    //using  for loop for calculating sum of first n even numbers 
    for ($i = 1; $i <= $n; $i++) { 
        $sumEven += $currEven; 
  
        // next even number 
        $currEven += 2; 
    } 
  
echo "Sum of first  $n  even numbers is  :  ".$sumEven ;
      

?> 

Second method – using formula :

You can calculate some of first n numbers using formula, see the code below :

<?php

$n = 20; 
// using formula for calculating sum of first n even numbers 
$sum= ($n * ($n + 1)); 
echo "Sum of first   $n   even numbers is  :  $sum" ;
   
  

?> 

Comment here

− 1 = 6