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=?'
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=?'
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;
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);
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.
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 ;
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
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;
?>
<?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 ;
?>
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);
}
}
?>