can someone explain me something | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 2

can someone explain me something

my boy told me that if we put on a chess board' square a grain of rice then double it, at the end of the 64th square there is enough rice to feed few 1000's people. for fun we tried to code this as shown, i know it writes $rice every time but the result is correct but if i write the echo line after the while statement, i get one line but the answer is wrong $rice=1; $square=1; do{ echo "$rice <br/>"; $square++; $rice*=2; } while($square<=64);

30th Apr 2017, 11:15 AM
Nico Fileccia
Nico Fileccia - avatar
6 ответов
+ 7
In your while loop echo is before the multiplication, so after the last echo printed the variable $rise is doubled again. If you move the echo outside the while you will print the double of the last echo printed in the while loop. I hope this explain.
7th May 2017, 4:30 PM
Daniele Gaito
Daniele Gaito - avatar
30th Apr 2017, 11:22 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 5
If the echo is inside the loop, it gets called and executed with each iteration of the loop, assuming currently calculated variable $rice. If it is outside the loop, it is called only after iterating and ultimately calculating the $rice variable.
30th Apr 2017, 11:53 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 3
Yes, a do-while loop is first executed and only then the while condition is checked. Putting echo outside caused it to only be executed once. Right after the do-while loop ended.
30th Apr 2017, 12:08 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 2
what is the output you need and what output do you get? you know the do-while first executes the statement and then the check? try a while or for loop instead
30th Apr 2017, 11:20 AM
Harm Zeinstra
Harm Zeinstra - avatar
0
should have remembered that the loop is being excecuted before the condition is checked. Having $rice being printed after the do while loop caused $rice one time to many. is that correct?
30th Apr 2017, 12:06 PM
Nico Fileccia
Nico Fileccia - avatar