Jump to content

Noob Question: Adding values of an array togther.


ryandarin

Recommended Posts

Hi, Im sure there is an easier way to do this then how I am, so what would be the best/easiest way to add the numbers 1-100 (For example adding 1-10 would be 1+2+3+4+5+6+7+8+9+10 = 55) The way I was trying to do it was by using [code]<? foreach (range(0, 100) as $range) { ;
}[/code] Then im not sure how to add the values to one another, someone help a noobie out :D
Please tell me if you need more information or anything.
Link to comment
Share on other sites

[quote author=jesirose link=topic=123230.msg509059#msg509059 date=1169272328]
php.net/array_sum

or:
[code]$sum = 0;
foreach (range(0, 100) as $range) {
   $sum = $sum+$range;
}
print $sum;[/code]

ps: good use of range.
[/quote]
Thanks so much!
Sorry to be a bother again, but I have another question. Now im trying to add the squares of each number togther, yet this doesn't seem to be working correctly. ([i]Example of this again would be 1² + 2² + ....+ 10² = 385[/i])
[code]
$sum = 0;
foreach (range(0, 100) as $range) {
  $sum = $sum+pow($range, 2);
  }

[/code]
Link to comment
Share on other sites

What isn't working correctly?

I'd do[code]
$sum = 0;
foreach (range(0, 100) as $range)
  $sum = $sum+($range*$range);
//If you wanted to check each one as it goes
// print $sum.'<br />';
}
//or possibly
$nums = array();
for($i=0, $i<=100; $i++){
  $nums[] = $i*$i;
}
print array_sum($nums);
[/code]

Are we doing math homework? :-P
Link to comment
Share on other sites

[quote author=jesirose link=topic=123230.msg509193#msg509193 date=1169313535]
Are we doing math homework? :-P
[/quote]
Ok I guess it was woring all along, I must have made a mistake the first time I ran it, and no, not math homework :P. I thought doing the problems here http://projecteuler.net/ would be a good way to learn/practice php.
Link to comment
Share on other sites

No problems. It was probably a syntax error or something.
My favorite way to practice is to make games - much funner than math.  Here's a list of great games fit for programming: http://www.atariarchives.org/basicgames/index.php
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.