Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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