I tried to sum up all even numbers from 0 to 200 and I found 2 possible working ways, however the third method (the most efficient one) gives me a headache. Here's what I did so far:
First method:
$total = 0;
$number = 0;
while ($number < 200)
{
if ($number % 2 == 0)
{
$total = $total + $number;
}
$number++;
}
echo $total;
Second method:
$total = 0;
for($number = 0; $number < 200; $number+=2)
{
$total += $number;
}
echo $total;
Third method (can't get it to work)
echo array_sum(range(1,200,2));
How should I change my last method so that it works as intended?
Edit: Seems that none of the methods work: the output should be 10100 but it is 9900 for the first two methods and 10000 for the third.
You need to use
echo array_sum(range(0,198,2));
or
echo array_sum(range(0,199,2));
Its because the above function will sum up the values upto
200
whereas within yourwhile
andfor
loop will count upto198
only as you have specifically defined
$number < 200
begin from 0 but 1
echo array_sum(range(0,200,2));
result 10100
In the two methods that you tried, you have a condition that the number should not exceed more than 200. I also used the same scenario here.
echo array_sum(range(0,199,2));
Gives the expected output of 9900.
But the Correct answer is 10100.
To get 10100, We need to replace 199 with 200.
The formula (Mathematically)
2+4+6+8+10+..............+198+200 = 2(1+2+3+4+5+.....+100)
= 2 ((100*101)/2) (Formula: n(n+1)/2; n is the last term)
= 100*101
= 10100