werushka Posted March 17, 2009 Share Posted March 17, 2009 I am trying to find Sum of odd numbers from 1 to 100 I have the following code which I came up so far but can't figure the rest <?php for($n=0; $n<100; $n++) { if ($n % 2 != 1) { continue; } echo "$n"; } ?> I would appreciate some help Quote Link to comment Share on other sites More sharing options...
shlumph Posted March 17, 2009 Share Posted March 17, 2009 You need a variable to hold the sum... <?php //Before the loop $sum = 0; //Then in the loop $sum += $n; //(or $sum .= $n I forget PHP) Quote Link to comment Share on other sites More sharing options...
corbin Posted March 17, 2009 Share Posted March 17, 2009 $sum = 0; for($i = 1; $i < 100; $i+=2) { $sum += $i; } Is probably the quickest way. Quote Link to comment Share on other sites More sharing options...
trq Posted March 17, 2009 Share Posted March 17, 2009 Even quicker I should imagine..... echo array_sum(range(1,100,2)); Quote Link to comment Share on other sites More sharing options...
corbin Posted March 17, 2009 Share Posted March 17, 2009 Oooo didn't know about the third param of range. Quote Link to comment Share on other sites More sharing options...
trq Posted March 17, 2009 Share Posted March 17, 2009 Ive way too much time on my hands. Quote Link to comment Share on other sites More sharing options...
corbin Posted March 17, 2009 Share Posted March 17, 2009 So it would seem ;p. 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.