Course contentsShow
← C
Lesson 294 of 1,2194. Control FlowFree lesson

Using continue to skip invalid data entries

Using continue to skip invalid data entries

What you'll learn: How to use the continue statement to instantly jump to the next iteration of a loop when encountering data that shouldn't be processed.

The "Skip" Button for Loops

Imagine you are sorting through a basket of apples to make a pie. You pick up an apple, check it, and if it’s good, you peel it and slice it. But what if you pick up one that is completely rotten? You don't throw away the whole basket; you simply toss that one bad apple aside and immediately reach for the next one.

In C, the continue statement is your way of telling the program: "Stop what you're doing with this specific item and move straight to the next turn of the loop."

Unlike the break statement (which kills the loop entirely), continue acts like a shortcut. It skips all the code remaining in the current loop body and jumps back to the top to start the next iteration.

Seeing it in action

Let’s say you are writing a program that calculates the square root of numbers entered by a user. Since you cannot calculate the square root of a negative number in basic arithmetic, you want to skip any negative inputs without crashing the program.

#include <stdio.h>

int main() {
    int number;

    for (int i = 1; i <= 5; i++) {
        printf("Enter number %d: ", i);
        scanf("%d", &number);

        // Check for invalid data
        if (number < 0) {
            printf("Negative number detected. Skipping...\n");
            continue; // Jumps back to the start of the loop for the next 'i'
        }

        // This part only runs if the number is valid
        printf("The number is %d.\n", number);
    }

    return 0;
}

Why use it?

You might wonder why we don't just use an if-else block. While that works for simple cases, continue helps keep your code "flat" and readable.

By using continue to handle invalid data (often called "guard clauses"), you handle the errors early. This prevents your main logic from being buried deep inside nested curly braces. It allows you to keep the "good" path of your code easy to follow, while the "bad" data is flicked away as soon as it appears.

Key takeaway

The continue statement immediately ends the current loop iteration and jumps to the next one, making it perfect for filtering out invalid input.