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

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

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.