2

Can someone help me understand how to sum numbers?

For example, I want to use a for loop to sum all numbers from 1 to 10:

'1+2+3+4+5+6+7+8+9+10=?' 
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Anton Papazov
  • 85
  • 1
  • 2
  • 9

8 Answers8

6

Since you specifically said for loop:

<?php

$start = 1;
$end = 10;

$sum = 0;
for ($i = $start; $i <= $end; $i++) {
    $sum += $i;
}

echo "Sum from " . $start . " to " . $end . " = " . $sum;
Ananth
  • 4,227
  • 2
  • 20
  • 26
3

Yes, it is pretty easy to do:

array_sum(range(1, 10))

or

$sequence = array(1,2,3,4,5,6,7,8,9,10);
array_sum($sequence);
felipsmartins
  • 13,269
  • 4
  • 48
  • 56
3

Not sure if I understand the question or not, but

$sum = 0;

for ($i = 1; $i <= 10; $i++) {
   $sum += $i;
}

echo 'The sum: ' . $sum;

Should sum the numbers between 1 and 10 into the $sum variable.

Kakuriyo S
  • 51
  • 2
2

this will do ... you have a lot of options to do this

$a=0;
for($i=0;$i==10;$i++)
{
    $a=$a+$i;
}
echo 'Sum= ' . $a ;
Riad
  • 3,822
  • 5
  • 28
  • 39
Akhil Sidharth
  • 746
  • 1
  • 6
  • 16
2

In fact, using a loop for this is the least efficient way. This is an arithmetic sequence and can be calculated using the formula:

S = n*(a1+an)/2 

where a1 is first element, an is last element, n number of elements.

// for 1..10 it would be: 
$sum = 10*(1+10)/2; 

// for 1..2000 it would be:
$sum = 2000*(1+2000)/2; 

// u can use the same formula for other kinds of sequences for example:
// sum of even numbers from 2 until 10:
$sum = 5*(2+10)/2; // 5 elements, first is 2, last is 10
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
user1983515
  • 345
  • 1
  • 6
0

Try like this:

<form method="post">
Start:<input type="text" name="a">
End: :<input type="text" name="b">
<input type="submit" >
</form>

<?php

$start = $_POST['a'];
$end = $_POST['b'];

$sum = 0;
for ($i = $start; $i <= $end; $i++) {
    $sum += $i;
}

echo "<h2>Sum from " . $start . " to " . $end . " = " . $sum;


?>
Shyful66
  • 1
  • 5
0
<?php

    $array = array(1,2,3,4,5,6,7,8,9,10);  
    $count = count($array);

    $sum = 0;

    for($i=0;$i<$count;$i++){
      $sum  += $array[$i];
    }
    echo $sum ;
?>
Zhorov
  • 28,486
  • 6
  • 27
  • 52
-1

Make 1+2+3+4+5 = ? by recursion function

<?php
    $n=1;
    echo Recursion($n);
    function Recursion($n){
        if ($n <=5){
            if($n<5){
                echo "$n+";
            }
            else echo "$n=";
        return $n+Recursion($n+1);
        }
    }
    ?>
raqibnur
  • 59
  • 1
  • 7
  • Please add some explanation to your answer such that others can learn from it - why should recursion help in any way here? There is no, absolutely no benefit of using recursion here – Nico Haase May 23 '20 at 21:11