C++ course(sixth section)
Break & Continue Statements
A break and continue statement alters the flow of control
The break statement, when executed in a switch structure, provides an immediate exit from the switch structure
The break statement can be used in while, for, and do...while loops
When the break statement executes in a repetition structure, it immediately exits from these structures.
The break statement is typically used for two purposes:
1. To exit early from a loop
2. To skip the remainder of the switch structure
After the break statement executes, the program continues to execute with the first statement after the structure
The use of a break statement in a loop can eliminate the use of certain (flag) variables.
The continue statement is used in while, for, and do-while structures
When it is executed in a loop, it skips the remaining statements and proceeds with the next iteration of the loop
In a while and do-while structure, the expression (loop-continue test) is evaluated immediately after the continue statement
In a for structure, the update statement is executed after the continue statement, and then the loop condition executes.
for (int x=1;x<=5; x++)
if (x!=2)
cout<<x<<“\t”;
else
break;
if (x!=2)
cout<<x<<“\t”;
else
continue;
cout<<x<<endl;
Output:
1 3 4 5 6
Break & Continue Statements
The break statement, when executed in a switch structure, provides an immediate exit from the switch structure
The break statement can be used in while, for, and do...while loops
When the break statement executes in a repetition structure, it immediately exits from these structures.
1. To exit early from a loop
2. To skip the remainder of the switch structure
After the break statement executes, the program continues to execute with the first statement after the structure
The use of a break statement in a loop can eliminate the use of certain (flag) variables.
When it is executed in a loop, it skips the remaining statements and proceeds with the next iteration of the loop
In a while and do-while structure, the expression (loop-continue test) is evaluated immediately after the continue statement
In a for structure, the update statement is executed after the continue statement, and then the loop condition executes.
Examples:
1)for (int x=1;x<=5; x++)
if (x!=2)
cout<<x<<“\t”;
else
break;
cout<<x<<endl;
Output:
1 2
2)
for (int x=1;x<=5; x++) if (x!=2)
cout<<x<<“\t”;
else
continue;
cout<<x<<endl;
Output:
1 3 4 5 6
0 comments:
Post a Comment