gibbonsec Posted February 5, 2010 Share Posted February 5, 2010 Asked to use a while loop to sum all numbers 1-10. Obviously the value should come out to 55. Mine comes out to 65. What the heck am I doing wrong?? <?php $counter = 1; while ($counter <= 10){ echo $counter; echo "<br />"; $counter = $counter + 1; $total = $total + $counter; } echo "<br />"; echo "<b>The total is: $total</b>" ?> Any help would be appreciated. I'm sure it's something ridiculously simple I'm missing. Quote Link to comment https://forums.phpfreaks.com/topic/191076-new-to-programming-very-easy-question/ Share on other sites More sharing options...
PFMaBiSmAd Posted February 5, 2010 Share Posted February 5, 2010 Step through your code and determine what value is in $counter when it gets added to $total the first time through the loop? I'm going to guess that it should be 1 instead of 2 because you need to increment $counter after you add it to $total. Quote Link to comment https://forums.phpfreaks.com/topic/191076-new-to-programming-very-easy-question/#findComment-1007532 Share on other sites More sharing options...
gibbonsec Posted February 5, 2010 Author Share Posted February 5, 2010 That did it! Swapped the $total and $counter variables' order in the loop and we're good now. Knew it was something simple. Thanks again! <?php $counter = 1; while ($counter <= 10){ echo $counter; echo "<br />"; $total = $total + $counter; $counter = $counter + 1; } echo "<br />"; echo "<b>The total is: $total</b>" ?> Quote Link to comment https://forums.phpfreaks.com/topic/191076-new-to-programming-very-easy-question/#findComment-1007534 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.