Hello, I want to know what is wrong in my program | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Hello, I want to know what is wrong in my program

This program calculate how day take a snail to be out, in day he run 7 feet and at night -2 function main() { var di = parseInt(readLine(), 10); var s=0 var f; var d=0; do{ d=d+1 f=s+7; if (f==di){ console.log(d) break; } s=f-2; }while (s!=di); if (s==di){console.log(d)} }

24th Nov 2022, 9:00 PM
BOUSSEKINE WISSAL
BOUSSEKINE WISSAL - avatar
7 Answers
+ 3
f value can exceed the di . Then there is no stoping loop. Use >= instead of == , in if condition. And no need to print d again out side loop.
24th Nov 2022, 9:07 PM
Jayakrishna 🇮🇳
+ 3
function main() { var di = parseInt(readLine(), 10); var s=0 var f; var d=0; do{ d=d+1 f=s+7; if (f >=di ){ console.log(d) break; } s=f-2; }while (s!=di); //if (s==di){console.log(d)} } See if you use if( f==di) break ; Then what if example di = 30 but f = 34 , you should break the loop as it reaches depth already. But f==di is not true so it won't stop loop and s!=di (32!=30) is true so it continues loop so never after f==di comes true. Then it is infinite loop. You must use condition if( f >= di) break; And if you print day value before break then no need to print after loop. Of course if condition is false though. So Never print I think.
24th Nov 2022, 9:35 PM
Jayakrishna 🇮🇳
+ 2
Thank you, in the first time I guessing that you talk about the second if sorry But I don't understand why my first solution is wrong can you explain please because I really need the answer.
24th Nov 2022, 9:21 PM
BOUSSEKINE WISSAL
BOUSSEKINE WISSAL - avatar
+ 1
It said in output "execution timed out "
24th Nov 2022, 9:11 PM
BOUSSEKINE WISSAL
BOUSSEKINE WISSAL - avatar
+ 1
Yes. It is because infinite looping.. Read my reply ☝again for solution.
24th Nov 2022, 9:14 PM
Jayakrishna 🇮🇳
+ 1
Thank you very much for help,
24th Nov 2022, 9:37 PM
BOUSSEKINE WISSAL
BOUSSEKINE WISSAL - avatar
+ 1
Side note: get used to using meaningful variable names. They help a lot in debugging.
25th Nov 2022, 4:02 AM
Emerson Prado
Emerson Prado - avatar