Continue Statement Work

·

2 min read

Imagine you’re a teacher checking homework assignments for your students.

You have a stack of papers on your desk, and you’re going through them one by one. For each paper, you check if the student has written their name. If a name is missing, you put the paper aside to talk to the student later, and then you continue with the next paper. You don’t spend any more time on the paper with the missing name; you immediately move on to the next one.

In this story, the process of checking papers is like a loop in a program, and each paper is like an iteration of the loop. The action of putting a paper aside and moving on to the next one is like the continue statement.

Now, let’s look at a code example:

#include <stdio.h>

int main() {
    for (int i = 0; i < 10; i++) {
        if (i % 2 == 0) {  // If the number is even
            continue;  // Skip the rest of this iteration and move on to the next one
        }
        printf("%d\n", i);  // This line is only reached if the number is odd
    }
    return 0;
}

In this C program, we have a for loop that iterates over the numbers from 0 to 9. For each number, it checks if the number is even. If the number is even, it executes the continue statement, which skips the rest of the current iteration and immediately starts the next one. This means that the printf statement is only executed for odd numbers. So, the output of this program will be the odd numbers from 0 to 9.

Did you find this article valuable?

Support SAHIL ALI by becoming a sponsor. Any amount is appreciated!