Loop control statements change the normal sequential execution of loops, giving the programmer precise control over when a loop terminates or skips an iteration.
1. The break Statement
The break statement is used to immediately terminate the innermost loop (or switch statement) it is contained within. Execution proceeds to the statement immediately following the loop body.
Use Case: Exiting a Loop Early
This is often used when a condition is met inside the loop that makes further iteration unnecessary (e.g., finding a target value).
int target = 5;
int i;
for (i = 1; i <= 10; i++) {
printf("Checking %d...\n", i);
if (i == target) {
printf("Target found!\n");
break; // Exit the loop entirely
}
}
printf("Loop finished.\n");
// Output stops after checking 5.
2. The continue Statement
The continue statement skips the remaining code inside the current iteration of a loop and immediately proceeds to the next iteration.
Use Case: Skipping Code Blocks
This is often used to bypass specific iterations that meet a certain condition (e.g., skipping odd numbers or corrupted data).
int i;
for (i = 1; i <= 5; i++) {
if (i % 2 != 0) { // Check if 'i' is odd
continue; // Skip the rest of the current iteration
}
printf("Even number: %d\n", i);
}
// Output: Even number: 2, Even number: 4
3. The switch Statement
The switch statement is a multi-way decision structure that is often more readable and efficient than a long if-else if-else chain, especially when testing a single variable against many discrete integer or character values.
Key Components
switch (expression): The integer or character expression whose value is tested.case constant: Marks a block of code to execute if the expression matches the constant.break: Essential! Prevents execution from “falling through” to the nextcaseblock.default: Optional block executed if none of thecaseconstants match the expression (similar to the finalelse).
Example
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good Job.\n"); // This code executes
break;
case 'C':
printf("Passed.\n");
break;
default:
printf("Needs improvement.\n");
}
// Output: Good Job.
Crucial Detail: If you forget the
breakstatement in acaseblock, execution will “fall through” and execute the code in the subsequentcaseblocks until abreakor the end of theswitchis reached.
