Continue Statement in C
The continue statement is used to skip the current iteration of a loop and move to the next iteration immediately.
Syntax:
continue;
Example 1: continue statement in for loop
#include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip the iteration when i is 3 } printf("Iteration: %d\n", i); } return 0; }
Output:
1 2 4 5
Example 2: continue statement of skip negative numbers and sum.
#include <stdio.h> int main() { int n, sum = 0; for (int i = 1; i <= 5; i++) { printf("Enter a number (%d/5): ", i); scanf("%d", &n); if (n < 0) { // If the number is negative, skip it printf("Negative numbers are not allowed. Skipping...\n"); continue; } sum += n; // Add positive number to sum } printf("Total Sum of Positive Numbers: %d\n", sum); return 0; }
Output:
Enter a number (1/5): 1 Enter a number (2/5): -5 Negative numbers are not allowed. Skipping... Enter a number (3/5): -3 Negative numbers are not allowed. Skipping... Enter a number (4/5): 4 Enter a number (5/5): 6 Total Sum of Positive Numbers: 11
Explanation :
You are writing a program that asks the user for numbers. The program ignores negative numbers but continues adding positive numbers to a total sum.
When to Use continue?
Skipping invalid user inputs (like negative numbers in this case).
Skipping unnecessary iterations in loops (e.g., ignoring weekends in a work schedule).
Filtering out unwanted data in file reading or database processing.