Programmer Coding

Break / Continue in C Lannguage

Break and Continue Statements

Sometimes, due to an exceptional condition, you need to jump out of a loop early, that is, before the main controlling expression of the loop causes it to terminate normally. Other times, in an elaborate loop, you may want to jump back to the top of the loop (to test the controlling expression again, and perhaps begin a new trip through the loop) without playing out all the steps of the current loop. The break and continue statements allow you to do these two things.

  • Break Statements

In C, the break statement is used to terminate the execution of the nearest enclosing loop in which it seems. we’ve got already seen its use inside the transfer announcement. The break statement is widely used with for, at the same time as, and do–while loops. while the compiler encounters a break statement, the control passes to the assertion that follows the loop wherein the wreck assertion appears. Its syntax is pretty simple, simply type key-word break followed through a semi-colon.

Example

#include <stdio.h>

int main() {

int i;

// Print numbers from 1 to 10, but stop when 5 is encountered

for (i = 1; i <= 10; i++) {

if (i == 5) {

// Exit the loop if i is equal to 5

break;

}

printf(“%d “, i);

}

return 0;

}

Output

1 2 3 4

  • Continue Statements

The continue statement is a control statement in C programming used in a loop to skip the remaining code in the current iteration’s loop and jump to the next iteration. It is especially useful when you want to skip some repetitions on a case-by-case basis without breaking the loop.

Example

#include <stdio.h>

int main() {

int i;

// Print odd numbers from 1 to 10, skipping even numbers

for (i = 1; i <= 10; i++) {

if (i % 2 == 0) {

// Skip even numbers

continue;

}

printf(“%d “, i);

}

return 0;

}

Output

1 3 5 7 9

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top