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 Link to comment https://forums.phpfreaks.com/topic/149745-php-101-sum-of-odd-numbers-from-1-to-100/ 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) Link to comment https://forums.phpfreaks.com/topic/149745-php-101-sum-of-odd-numbers-from-1-to-100/#findComment-786344 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. Link to comment https://forums.phpfreaks.com/topic/149745-php-101-sum-of-odd-numbers-from-1-to-100/#findComment-786345 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)); Link to comment https://forums.phpfreaks.com/topic/149745-php-101-sum-of-odd-numbers-from-1-to-100/#findComment-786352 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. Link to comment https://forums.phpfreaks.com/topic/149745-php-101-sum-of-odd-numbers-from-1-to-100/#findComment-786356 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. Link to comment https://forums.phpfreaks.com/topic/149745-php-101-sum-of-odd-numbers-from-1-to-100/#findComment-786357 Share on other sites More sharing options...
corbin Posted March 17, 2009 Share Posted March 17, 2009 So it would seem ;p. Link to comment https://forums.phpfreaks.com/topic/149745-php-101-sum-of-odd-numbers-from-1-to-100/#findComment-786398 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.