The ‘continue’ Keyword in C Programming

C Programming @ Freshers.in

In C programming, the ‘continue’ keyword is a versatile control statement that allows you to influence the flow of loops. This article offers an in-depth explanation of the ‘continue’ keyword, its role in loop control, and provides real-world examples to showcase how it enhances the efficiency and readability of your code.

Understanding the ‘continue’ Keyword

The ‘continue’ keyword in C is used within loops to skip the remaining code within the current iteration and proceed to the next iteration. It effectively lets you skip specific iterations based on a condition, improving the control and efficiency of loops.

Syntax:

for (initialization; condition; increment) {
    // Code before 'continue'
    if (condition_to_skip_iteration) {
        continue;
    }
    // Code after 'continue' (skipped if 'condition_to_skip_iteration' is true)
}

Example 1: Using ‘continue’ in a Loop

#include <stdio.h>
int main() {
    for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            continue; // Skip iteration when i equals 3
        }
        printf("%d ", i);
    }
    return 0;
}

Output:

1 2 4 5

In this example, the ‘continue’ statement is triggered when i equals 3, causing the loop to skip that iteration and proceed to the next. As a result, the numbers 1, 2, 4, and 5 are printed, excluding 3.

Common Use Cases for ‘continue’

  1. Skipping Specific Iterations: ‘continue’ is used to skip certain iterations of a loop when a specific condition is met, allowing you to control which iterations execute.
  2. Filtering Data: ‘continue’ is valuable for filtering data within loops, where you want to exclude elements based on certain criteria.

Example 2: Filtering Odd Numbers

#include <stdio.h>
int main() {
    for (int i = 1; i <= 10; i++) {
        if (i % 2 != 0) {
            continue; // Skip odd numbers
        }
        printf("%d ", i);
    }
    return 0;
}

Output:

2 4 6 8 10

In this example, ‘continue’ is used to skip iterations when i is an odd number, resulting in the printing of even numbers from 1 to 10.

Author: user