0
What is the output of this code and how many times will the loop execute?
int p=200; while(true){ if(p<100) break; p-=20; } System.out.println(p);
1 Odpowiedź
+ 3
First run, the loop runs and p is not less than 100 so the if statement is not executed, 20 is taken away from p (p = 180).
Second run, the loop runs and p is not less than 100 so the if statement is not executed, 20 is taken away from p (p = 160).
Third run, the loop runs and p is not less than 100 so the if statement is not executed, 20 is taken away from p (p = 140).
Fourth run, the loop runs and p is not less than 100 so the if statement is not executed, 20 is taken away from p (p = 120).
Fifth run, the loop runs and p is not less than 100 so the if statement is not executed, 20 is taken away from p (p = 100).
Sixth run, the loop runs and p is still not less than 100 (100 is equal to 100) so the loop is not executed, 20 is taken away from p (p = 80).
Seventh run, the loop runs and p is now less than 100 (80 < 100) so the if statement executes and the loop is broken out of and the value of p is outputted.
So to summarize, the output is 80 and the loop runs 7 times.