+ 1

Well I did it ..but I don't understand why it print 5 ..not 1 at the end ..and also why don't it print finished at the end

https://code.sololearn.com/cri36cRQtiRY/?ref=app

22nd Jul 2018, 10:04 AM
Deesha Devi Raghu
Deesha Devi Raghu - avatar
2 odpowiedzi
+ 2
You declare a variable i in the first line and set it to 1. In line 5, you increase it (i = i + 1). In the whole code, there's no statement to decrease i (i = i - 1) or to set i to 0 (i = 0). So the variable i can never be 0 and lines 9-13 will never be executed. The while statement is executed as long as i is smaller or equal to 5. Note that you print 'finished' before (!) you increase i. That's why it will print 4 as the last number before it prints 'continue' (line 9 of the output). By the time 'continue' is printed, i already has the value 5 though (the value 5 just isn't printed because you print the value of i before you increase it). The continue statement in line 8 will 'throw you back' before the beginning of the loop, so 'continue' is printed twice and i increased another time. Now, the initial condition 'i <= 5' isn't true anymore because i is 6. So the whole loop finishes. Maybe it's easier to understand if you switch lines 3 and 5 and you increase the value of i before increasing it.
22nd Jul 2018, 10:30 AM
Anna
Anna - avatar
+ 1
Hi Daya! Your loop keeps incrementing i by 1 until it's >5. Things go normally till i=4. When i=4, after printing 4 and "finished", i is incremented to 5. Now the if condition in line 6 becomes true, so "continue" is printed. Then because of the continue statement, the flow immediately goes back to the beginning of while loop at line 2. The while condition is still true (since 5<=5), so we print 5 and "finished", and increment i to 6. Again the first if condition is true, so "continue" is printed, and then encountering the continue statement, we go back to line 2. But now i is 6, which is not <=5. So we get out of the while loop. Since there's no more code after the while block, we stop. The condition "if i==0" is not even checked as it comes after the continue statement! It'd be false anyway since i is never 0, so the following block is never executed. Edit: I didn't see Anna's response when I wrote this. She's already said everything I wanted to say. Anyway, let us know if everything makes sense :)
22nd Jul 2018, 10:40 AM
Kishalaya Saha
Kishalaya Saha - avatar