+ 2

How can we jump out of loop after success of if statement inside??

3rd Jan 2017, 1:39 AM
Sajan
Sajan - avatar
4 Answers
+ 4
you can use break statement. for(...){ if(...){ break; } }
3rd Jan 2017, 1:47 AM
lowshuen
+ 2
you can use a break statement to jump out of the loop completely or you can use continue to break out of the current iteration and pick up with the next iteration. for (int x = 0; x < 20; x++){ if (x == 10){ break; } System.out.print(x + " "); } This example ends the loop once x becomes 10 despite the loop control expecting to go up to 19 (x < 20) This loop prints out: 1 2 3 4 5 6 7 8 9 10 for (int x = 0; x < 20; x++){ if (x == 10){ continue; } System.out.print(x + " "); } This example skips out of the iteration once the x value equals 10 but picks back up with 11 This loop prints out: 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19
3rd Jan 2017, 2:22 AM
Pat Gekoski
Pat Gekoski - avatar
+ 1
Depend on what you want to do, if you use the break keyword it will come out of the loop(stopping the current execution flow) and still execute the remaining code in the method, but if you use return it will go back to the calling function and it will not execute the remaining code in the block. The answer for Java.
3rd Jan 2017, 2:17 AM
joseph odibo
joseph odibo - avatar
+ 1
thank you guys for your precious answer
3rd Jan 2017, 3:23 AM
Sajan
Sajan - avatar