Breaking

Sunday, March 8, 2020

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

To get the sum of the first 20 even numbers, we need to first understand what is even number.

Let's understand is what is even number?

Even number is any integer that can be divided exactly by 2.

So, Let's understand the meaning of it using an example-

$x = 2;
if($x % 2 ==0) {
   echo 'This is even number';
}

OR

$x = 4;
if($x%2 == 0) {
   echo 'This is even number';
}

and so on. So basically, all the numbers which are multiples of 2 are even numbers here.

Now, let's jump into the question to find out the first 20 even numbers.

function get_sum($nm) {
    $sum = 0;
    $curr_even_nm = 2;
    for ($i = 0; $i < $nm; $i++)
    {
        $sum += $curr_even_nm;
        $curr_even_nm += 2;
    }
    return $sum;
}
echo get_sum(5);

Let's understand code -
In the function, we have defined $sum = 0 whose value will be updated in the loop. Then as we know that we are adding even numbers, so initializing $curr_even_nm = 2 to make sure that 2 will be added in the loop every time.
Now, in the loop, we have updated $sum +=$curr_even_nm every time for loop executes and $curr_even_nm will be updated to next even number.
In this way, once for loop completes, we will get $sum with the desired number and this value will be return to the calling function get_sum().



No comments:

Post a Comment