Jump to content

How can I make this flow control statement more efficient?


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 :)

The if() statement is unnecessary. The while() loop will ensure that $num will be >99 before it gets past the while. But, I don't think that loop is even necessary. Let me see if there is a math function to do that addition automatically.

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

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.