C Programming Language Tutorial
Variables and Data Types
Input/Output
Looping and Selection Structures
Array
Functions
Preprocessing Command
Pointer
Structure
File Operations
Important Knowledge
In C programming, break
and continue
are control statements used to alter the flow of loops. They provide additional control over the execution of loop statements such as for
, while
, and do-while
.
break
statementThe break
statement terminates the innermost loop in which it is placed and transfers the control to the statement immediately following the loop. This is useful when you want to exit a loop before its completion based on a specific condition.
Syntax: break;
Example:
#include <stdio.h> int main() { for (int i = 1; i <= 10; i++) { if (i == 6) { break; // Break the loop when i is 6 } printf("%d ", i); } return 0; // Output: 1 2 3 4 5 }
continue
statementThe continue
statement skips the rest of the current loop iteration and transfers the control to the beginning of the next iteration. This is useful when you want to skip certain iterations based on a specific condition.
Syntax: continue;
Example:
#include <stdio.h> int main() { for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; // Skip the loop iteration when i is an even number } printf("%d ", i); } return 0; // Output: 1 3 5 7 9 }
In summary, the break
statement allows you to exit a loop prematurely based on a specific condition, while the continue
statement helps you skip specific iterations without exiting the loop. Understanding these control statements is essential in C programming, as they provide greater flexibility in managing loop execution.
How to break out of a loop in C:
#include <stdio.h> int main() { for (int i = 1; i <= 5; ++i) { if (i == 3) { break; // Exit the loop when i is 3 } printf("%d ", i); } return 0; }
break
to exit a loop when a specific condition is met.continue
statement for skipping iterations in C:
#include <stdio.h> int main() { for (int i = 1; i <= 5; ++i) { if (i == 3) { continue; // Skip the rest of the loop for i = 3 } printf("%d ", i); } return 0; }
continue
to skip iterations in a loop.Infinite loop termination using break
in C:
#include <stdio.h> int main() { int count = 0; while (1) { printf("Inside infinite loop\n"); ++count; if (count >= 5) { break; // Terminate the loop after 5 iterations } } return 0; }
break
to terminate an infinite loop.