The branching statements are used to take the control of the program to elsewhere in the program. There are three branching statements. They are :
- break
- continue
- goto and labeled statements
- 1. break :
- The break statement is used to terminate the current iteration and passes the control to the subsequent statements. It is most frequently used within the switch statement to terminate the current case and so the following case does not start executing its statement.
The following example demonstrates the break statement :#include<stdio.h> void main() { int i=5; printf("\n Demonstration of break statement "); while(1) { printf("\n %d ",++i); /* Increments the value of i and then prints the value */ if(i==10) break; /* Loop terminates when the value of i reaches 10 */ } printf("\n Loop terminated at i = %d",i); }
Output : Demonstration of break statement 6 7 8 9 10 Loop terminated at i = 10
- 2. continue
- The 'continue' statement is used to skip the current iteration and continue with the next iteration based on the condition specified.
An illustration will be helpful to understand this :/* Printing the odd numbers from 1 to 10 */ #include<stdio.h> void main() { int i; printf("\n Demonstration of continue statement "); for(i=1;i<=10;i++) { if(i%2==0) /* If i is even, then move on to next iteration */ continue; printf("\n %d ",i); } }
The output of the above program will be :Demonstration of continue statement 1 3 5 7 9
- 3. goto and labeled statements
- The goto statement is used to transfer the execution of the program to a label. The following limitations apply when using goto and labeled statements:
- The label used is unique i.e. only one label name should be used within a function.
- The branching can be done only within a function. i.e. goto statement and its label should be present within the same function.
/* Print numbers from 1 to 5 */ #include<stdio.h> void main() { int i=0; printf("\n Demonstration of goto and labels "); while(1) { printf("\n %d ",++i) if(i==5) goto abc; /* Transfer control to label 'abc' } abc: printf("\n Iteration stopped at i = %d ",i); /* Control is transferred here */ }
Demonstration of goto and labels 1 2 3 4 5 Iteration stopped at i = 5
No comments:
Post a Comment