Jordan
Jordan

Reputation: 13

Php subtraction and adding sum

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.

Upvotes: 1

Views: 896

Answers (1)

Patrick Q
Patrick Q

Reputation: 6393

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

Upvotes: 1

Related Questions