Break statement is used to break the execution of the loop. In another words, break statement is use to terminate a loop(while, do while and for) and switch case only. In case of Nested loops, it terminates the control of inner loop only.
Example 1: Program to explain the use of Break statement.
void main() { int i; clrscr(); for(i=1;i<=10;i++) { if(i==5) break; //move the controller, outside loop (line #11) printf("%d ",i); } printf("\nEnd of the program"); getch(); }
Example 2: Use of Break statement in Nested Loop.
void main() { int i; clrscr(); for(i=1;i<=5;i++) //outer loop { for(j=1;j<=5;j++) //inner loop { if(j==2) break; //break inner loop, send controller to outer loop printf("%d ",i); } } getch(); }
Continue is used to skip the statements. If we don't want to write any statement inside a condition then we can use continue statement.
In other words: continue statement takes the control to the beginning of the loop.
Example 3: Program to explain the use of Continue statement.
void main() { int i; clrscr(); for(i=1;i<=10;i++) { if(i==5) continue; //send the controller to loop, line #5 printf("%d ", i); } printf("\nEnd of the program"); getch(); }
The goto statement can be use anywhere unconditionally in between the program. The goto statement is use to jump the control anywhere in between the program. The word followed by goto keyword is known as label.
Example 4: Program to explain the use of Goto statement.
void main() { printf("1st line"); goto end; //send the controller to label end printf("2nd line"); printf("3rd line"); end: }
Example 5: Program to explain the use of Goto statement.
void main() { int i; clrscr(); for(i=1;i<=10;i++) { printf("%d ", i); if(i==5) goto end; } end: printf("\nEnd of the program"); getch(); }
Example 6: Print counting 1 to 10 using goto function, without using any loop.
void main() { int counter=1; clrscr(); START: printf("%d",counter); counter++; if(counter<=10) goto START; getch(); }