Jump to content

New to programming: Very easy question


gibbonsec

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/191076-new-to-programming-very-easy-question/
Share on other sites

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.

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>"
        
        ?>

Archived

This topic is now archived and is closed to further replies.

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