+ 4

Why is the output 10, 20, 40 and not 20, 30, 40?

for(int x=10; x<=40; x=x+10) { if(x == 30) { continue; } System.out.println(x); }

2nd Mar 2018, 7:47 PM
Sebastian Sivertsen
Sebastian Sivertsen - avatar
4 odpowiedzi
+ 15
#continue statement makes the loop to process/jump to next iteration 1) x is 10 and x is not 30 prints 10 2)x=x+10 x=20 and x is not 30 prints 20 3) x=x+10 x=30 here if condition satisfied and by seeing continue statement it jump to next iteration ( so 30 will not be printed) 4)x=x+10 x=40 and x is not 30. prints 40
2nd Mar 2018, 7:59 PM
Hannah Grace
Hannah Grace - avatar
+ 4
It's because you're setting it up so that if the value of x is equal to 30, then the program skips that iteration and moves to the next one, not running any other statement within the for loop. Because of this, the value of x is not printed when it is equal to 30 resulting in it printing out what it does. Hope this helped! d:
2nd Mar 2018, 7:53 PM
Faisal
Faisal - avatar
+ 3
Now I understand it, thanks a bunch!
2nd Mar 2018, 8:01 PM
Sebastian Sivertsen
Sebastian Sivertsen - avatar
+ 2
Why is the output 10, 20, 40 and not 20, 30, 40? for(int x=10; x<=40; x=x+10) { if(x == 30) { continue; } System.out.println(x); } 1. the loop starts with x=10.........next it checks whether x=30...which is false hence prints 10 2. now the value of x is 20 .........next it checks whether x=30....which is again false hence prints 20 3.now the value of x is 30........... next it checks whether x=30...which is true...and hence the continue statement gets executed NOTE:The continue statement skips the current iteration of a loop (for, while, and do...while loop). When continue statement is executed, control of the program jumps to the end of the loop. Then, the test expression that controls the loop is evaluated. In case of for loop, the update statement is executed before the test expression is evaluated. hence 30 does not gets displayed 4.now the value of x is 40............which is not equal to 30...hence 40 gets displayed..... 5.now the value of x is 50.........which terminates the loop therfore the output is 10,20,and 40
3rd Mar 2018, 3:22 PM
Rupesh Mishra
Rupesh Mishra - avatar