Jump to content

Sum of adding consecutive numbers together


zender

Recommended Posts

Hey guys. Curious to see if I can get a little assistance with this.

I'm trying to build an array within a for loop that's going to output the sum of adding consecutive numbers together. The output should look like this -

[1] => 1

[2] => 3

[3] => 6

[4] => 10

 

and so forth, up to 100. This is what I have currently, but the only result I'm getting is

 

Array

(

    [100] => 5051

)

 

 

<?php

for($i=1; $i<=100; $i++)
{
    
             $sum += $i;
     $sum_array = array(
     $i => $sum
            );
}

print "<pre>";
print_r($sum_array);
print "</pre>";
?>

 

Any suggestions would be appreciated.

You keep on redefining the $sum_array in your loop. Initialize it outside the loop and use it inside the loop:

<?php
  $sum_array = array();
for($i=1; $i<=100; $i++)
{
             $sum += $i;
     $sum_array[$i] = $sum;
}

echo "<pre>" . print_r($sum_array,true) . '</pre>';
?>

 

Ken

 

[1] => 1

[2] => 3

[3] => 6

[4] => 10

Your array goes from 1 to 3 (diff of 2), 3 to 6 (diff of 3), 6 to 10 (diff of 4).
<?PHP
$out = array(0 => 1);
$diff = 2;
for($x = 1; $x <= 100; $x++) {
	array_push($out, $out[$x-1] + $diff);
	$diff++;
}
print_r($out);
?>

You keep on redefining the $sum_array in your loop. Initialize it outside the loop and use it inside the loop

 

Ken. Thanks a lot for that. I really appreciate it. I had a feeling that was the case, but I wasn't completely sure, obviously.

 

Zach, thanks for the helping hand as well.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.