Jump to content

How can I make this flow control statement more efficient?


APD1993

Recommended Posts

I have a flow control statement that has to write "1+2+3+4...+100" and then display the total (5050) on the webpage. The current code that I have is

    <html>
    <head><title>Adding Numbers Script</title></head>
    <body>
    <?php
    $num=0;
    $sum=0;
    while ($num<=99)
    {
        {$sum=$sum+$num++; echo "$num+ ";}
       
        }
        if ($num>99){$sum=$sum+$num; echo"$num= ";}
        echo "$sum";
    ?>
     
    </body>
    </html>

 

However, I was told that it could be made more efficient by only having one flow control statement in there, rather than the two I have at the moment (the while and the if statements). Can anyone help me make this more efficient?

 

Thanks in advance,

 

Andrew :)

Link to comment
Share on other sites

To get the final sum this is all you need

$first = 1;
$last  = 100;
$sum = (($last - $first + 1) * ($first + $last)) /2;
echo "Sum: {$sum}";

 

This adds all the consecutive numbers between the start number to the last number, i.e.

 

1 + 2 + 3 + . . . + 98 + 99 + 100 = 5050

Link to comment
Share on other sites

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.