Use of continue in c programming

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

 

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.

continue in c

 

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:

continue in c

 

Recommended Articles for you: