APD1993 Posted January 24, 2012 Share Posted January 24, 2012 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 https://forums.phpfreaks.com/topic/255694-how-can-i-make-this-flow-control-statement-more-efficient/ Share on other sites More sharing options...
Psycho Posted January 24, 2012 Share Posted January 24, 2012 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. Link to comment https://forums.phpfreaks.com/topic/255694-how-can-i-make-this-flow-control-statement-more-efficient/#findComment-1310782 Share on other sites More sharing options...
Psycho Posted January 24, 2012 Share Posted January 24, 2012 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 https://forums.phpfreaks.com/topic/255694-how-can-i-make-this-flow-control-statement-more-efficient/#findComment-1310794 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.