• A.razaq

T16-Break and Continue statements

we learned previously about breaks in the switch statement and if you remember we used them in switch to terminate matching and execution for the rest of the code

in this tutorial it has a similar function used in loops, we can also use break to jump from the loop

for example, if your loop begins from 0 to 10 and you want to exit the loop at 5 you can do that by using break , lets begin with an example.




for (int i = 0; i < 10; i++) {
			  if (i == 5) {
			    break;
			  }
			  System.out.println(i);
			}

the operator ( == ) means equal to

so in this case if ( i ) equals 5 ( i==5) , the loop will terminate


lets see the output:



as you can see, the condition is met and once i equals 5 the loop will terminate and end.

--------

now what if you want to skip only one iteration and continue the rest of the loop, for example lets say you want the loop to begin from 0 until 5 but skip 6 then continue to 10


like if you want the output to be like this for example


0
1
2
3
4
5
7
8
9
10 

in this case we use the continue statement to skip an iteration and resume the rest of the loop


lets take an example :




	for (int i = 0; i <= 10; i++) {
			  if (i == 6) {
			    continue;
			  }
			  System.out.println(i);
			  
			}

the output will be



as you can see, the condition is met when ( i ) was equal to (6) so continue statement will skip this value and resume the loop



5 views0 comments

Recent Posts

See All