3.C) Demonstrate the working of break and continue statement with a suitable example
Answer:-
Break and continue: break and continue are unconditional control constructs.
i. Break:-
This statement is useful to terminate a loop and transfer control out of the loop under special situations.
- break statement works with while, do….while, for, and switch statements.
- Following program syntax diagrammatically represents the working
- mechanism of a break statement.
Note: If a break statement is used in the nested loops, the control will come out
from the inner loop; still, the outer loop is active.
Working of break statement:
When condition2 is true the loop gets terminated and control is transferred to
statement5 (which is outside the loop). Here we can observe that even though
Example Program for Break:-
void main( )
{
int i; for(i=1;i<=5;i++)
{
if(i==3)
break; printf(“%d ”,i);
}
Output: 1 2
ii. Continue
- The statement is helpful to skip a particular set of statements in the loop body and to continue execution from the beginning of the loop.
- Following syntax clearly depicts how control shifts to the beginning of a loop on finding continue statement.
Working of continue statement:
When condition2 is true continue statement is executed which results in transfer
of control to beginning of while loop skipping statement4 and statement5.
Example Program for Continue:-
void main()
{
int i; for(i=1;i<=5;i++)
{
if(i==3) continue; printf(“%d ”,i);
}
Output: 1 2 4 5