We can terminate an iteration without exiting the loop body using the continue keyword. When continue (jump statement) execute within the body of the loop, all the statements after the continue will be skipped and a new iteration will start. In other words, we can understand that continue causes a jump to the end of the loop body.
Note: The one thing needs to remember to continue statement use only within the loop body.
Syntax,
continue;
Flowchart of continue in C
How does continue work in C?
In the below example, I am printing the value of data until its value is less than 5. But here I have used a continue statement in the loop (while loop) for the condition (data == 2). If the value of data becomes 2, then continue statement executes and it will break the iteration that means all the statements below the continue will be skipped.
#include <stdio.h> int main (void) { int data = 0; // while loop execution while(data < 5) { if( data == 2) { ++data; //terminate the iteration continue; } printf(" value of a: %d\n", data); ++data; } return 0; }
Output: You can see “2” is skipped.
Similar the above example, we can use the “continue” keyword with do while, and for loops.
Note: The continue statement only break the iteration.
When should we use continue in C?
Sometimes we require to break the iteration (in the code) but not the loops, in this scenario we should use continue keyword. In another word you can understand that we are used the continue statement in code when we realize that this iteration of the loop isn’t going to produce a useful result.
Suppose a scenario where we need to add only 5 positive integer numbers. Here we can handle the negative entered number by continue keyword.
#include <stdio.h> int main(void) { int data = 0; int loop = 5; int sum = 0; while(loop != 0) { printf("\nEnter the numbers = "); scanf("%d",&data); if (data < 0) /* skip negative elements */ continue; sum += data; /* sum positive elements */ --loop; } printf("Sum of 5 positive numbers: %d\n", sum); return 0; }
Output:
Recommended Articles for you:
- Use of break statement in C.
- Use of return statement in C.
- How to use if condition in C?
- How to use C if-else condition?
- How to use for loop in C?
- You should know while loop use.
- Use of the switch case in the C program.
- C language character set.
- Elements of C Language.
- Data type in C language.
- Operators with Precedence and Associativity.
- How to pass an array as a parameter?
- Memory Layout in C.
- File handling in C, In a few hours.
- Replacing nested switches with the multi-dimensional array
- How to access a two-dimensional array using pointers?
- Brief Introduction of switch case in C.
- 100 C interview Questions.
- Function pointer in c, a detailed guide.
- How to use the structure of function pointer in c language?
- Function pointer in structure.
- Pointer Arithmetic in C.
- Brief Introduction of void pointer in C.