ryandarin Posted January 20, 2007 Share Posted January 20, 2007 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 :DPlease tell me if you need more information or anything. Quote Link to comment Share on other sites More sharing options...
Jessica Posted January 20, 2007 Share Posted January 20, 2007 php.net/array_sumor:[code]$sum = 0;foreach (range(0, 100) as $range) { $sum = $sum+$range;}print $sum;[/code]ps: good use of range. Quote Link to comment Share on other sites More sharing options...
ryandarin Posted January 20, 2007 Author Share Posted January 20, 2007 [quote author=jesirose link=topic=123230.msg509059#msg509059 date=1169272328]php.net/array_sumor:[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] Quote Link to comment Share on other sites More sharing options...
Jessica Posted January 20, 2007 Share Posted January 20, 2007 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 Quote Link to comment Share on other sites More sharing options...
ryandarin Posted January 20, 2007 Author Share Posted January 20, 2007 [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. Quote Link to comment Share on other sites More sharing options...
Jessica Posted January 20, 2007 Share Posted January 20, 2007 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.