1. break – We can
use the break statements in the following cases.
- · Within the switch to stop fall through.
Example –
public class
Loop4 {
public static void
main(String[] args) {
int x=0;
switch(x)
{
case
0:
System.out.println(0);
case
1:
System.out.println(1);
case
2:
System.out.println(2);
break;
case
3:
System.out.println(3);
default:
System.out.println("default");
}
}
}
Output –
0
1
2
- · Inside the loop to break loop execution based on some condition.
Example –
public class
Loop5 {
public static void
main(String[] args) {
for(int i=0;i<10;i++)
{
if(i==6)
break;
System.out.print(i+" ");
}
}
}
Output –
0 1 2 3 4 5
- · Inside label blocks to break block execution based on some condition.
Example –
public class
Loop6 {
public static void
main(String[] args) {
int x=10;
e1:{
System.out.println("begin");
if(x==10)
break
e1;
System.out.println("end");
}
System.out.println("hello");
}
}
Output –
begin
hello
Note – These
are the only places where we can use the break statement. If we use anywhere
else then we will get compile time error.
Example –
public class
Loop7 {
public static void
main(String[] args) {
int x=10;
System.out.println("begin");
if(x==10)
break;
System.out.println("end");
System.out.println("hello");
}
}
2. continue statement – Sometimes, it is required to skip a part of the body of loop under
specific conditions. So, C supports continue
statement to overcome this anomaly. The working structure of continue is similar to that of break statement but the difference is
that it cannot terminate the loop. It causes the loop to be continued with next
iteration after skipping statements in between. Continue statement simply skips statements and continues next
iteration. It is the keyword of C and the task of this keyword is to transfer the
control of program at the beginning of the loop. Using continue is always optional
but it should be placed within the loop body only. In implementation where we
know the maximum number of repetitions but some condition is there where we
need to skip the statements from repetition condition is there where we need to
skip the statements from repetition process then go for continue.
Example –
public class
Loop8 {
public static void
main(String[] args) {
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
continue;
}
System.out.println("i value is : "+i);
}
}
}
Output –
i value is : 0
i value is : 1
i value is : 2
i value is : 3
i value is : 4
i value is : 7
i value is : 8
i value is : 9
Explanation –
1. A variable i of type int is
declared.
2. A for loop is started and is
initialized as 1 and condition is if i less than 10.
3. On the first cycle 0 is less
than 10, so the condition is satisfied. Upto 0,1,2,3,4 print in console.
4. When i value is 5 and 6. In
the for loop there is an if statement that states that if i equals to 5 or 6
then come out of the loop and when i becomes 7 then again it starts printing in
console.
No comments:
Post a Comment