Continue statement in c
In a loop, if a programmer wants to drop any iteration of the loop or, does not want to execute certain statements at that iteration, then the programmer can use the continue statement.
Continue statement is usually associated with if-statement.
Let us understand the continue statement with an example,
Example 1:
Quiz: print the odd numbers from 1 to 9 using the continue-statement.
#include<stdio.h> int main() { int i; for(i=1;i<=9;i++) { if(i%2==0) continue; printf("%d ",i); } return 0; } Output: 1 3 5 7 9 |
In the above program by using the continue-statement, we have printed the odd values from 1 to 9.
Here if the condition inside the if-statement is true then the
continue-statement will ignore all the statements after the continue statement
and the control will directly move towards the start of the for-loop with incrementation.
Example 2:
#include<stdio.h> int main() { int i,num; printf("Enter the number\n "); scanf("%d ",&num); printf("print the numbers from 1 to 10\n"); for(i=1;i<=10;i++) { printf("%d ",i); } printf("print the numbers from 1 to 10 except the num value\n"); for(i=1;i<=10;i++) { if(i==num) continue; printf("%d ", i); } return 0; } Output: Enter the number 5 print the numbers from 1 to 10 1 2 3 4 5 6 7 8 9 10 print the numbers from 1 to 10 except the num value 1 2 3 4 6 7 8 9 10 |
In the above program, the value assigned to num is compared with the ith value at the end of the program and, except the num value, all the values are printed from 1 to 10.
The program concludes that the continue-statement skips all the statements after the continue statement inside the loop and moves the control to the incrimination of ith value and again continues with the next iteration inside the loop.
Important points:
- The continue-statement can be used inside the while-loop, do-while loop, for-loop.
- We don’t use continue statement in switch case because continue-statement is specifically used in loops for not executing statements after it without breaking out of that loop. When the continue-statement is executed, it just starts the loop in its next iteration.
Post a Comment
Post a Comment