1
votes

I have to create a sum on php that goes like this

1+2-3+4-5+6-7+8-8+10

For far I got this:

<?php
$start = 1;
$n=10;
$sum = 0;
for($i=$start; $i <=$n; $i++){
$sum += $i;
}
echo "sum from " . $start . " to " . $n . " = " . $sum;
?>

I understand the php code is adding but I'm unsure how to switch between adding and subtracting as the sum continues. Thank you for answering my query.

1
8-8 should be 8-9? - B. Desai
Hello welcome to stackoverflow? Please visit How to ask and Asking .... why not break it into only additions and only subtractions ? This is definitely possible with what you know !! Have you searched on web for how to branch in php? - รยקคгรђשค
You have received three usable answers. If you do not get into the habit of accepting and up-voting answers, people are going to be less likely to help you in the future. - Patrick Q

1 Answers

1
votes

The logic should be, after adding 1, you add every even number and subtract every odd number. To do this, you make use of the modulo operator.

$start = 1;
$n=10;
$sum = 0;
for($i=$start; $i <=$n; $i++){
    // for 1 or any even number (use modulo operator to check remainder when dividing by 2), add to sum
    if($i == 1 || $i%2 == 0)
    {
        $sum += $i;
    }
    // for any other number (any non-1 odd number), subtract from sum
    else
    {
        $sum -= $i;
    }
}
echo "sum from " . $start . " to " . $n . " = " . $sum;

DEMO