In C, break and continue are control flow statements used to alter the normal flow of execution in loops. These are useful for controlling the behavior of loops when specific conditions are met.
The break statement is used to exit from a loop or a switch statement prematurely. It will terminate the loop and transfer control to the statement immediately following the loop.
Use break to stop the loop when a certain condition is met, like when you find a specific value or when itβs no longer needed to continue looping.
#includeint main() { for (int i = 1; i <= 10; i++) { if (i == 5) { break; // Stop the loop when i equals 5 } printf("%d\n", i); } return 0; }
i
equals 5, the break
statement will exit the loop, and no numbers greater than 4 will be printed.
The continue statement is used to skip the current iteration of the loop and move directly to the next iteration. Unlike break, continue doesnβt terminate the loopβit just bypasses the code that follows it for the current iteration.
Use continue when you want to skip a certain part of the loop without breaking it entirely. This is useful when you want to ignore certain conditions and continue the loop.
#includeint main() { for (int i = 1; i <= 10; i++) { if (i == 5) { continue; // Skip when i equals 5 } printf("%d\n", i); } return 0; }
continue
statement. It will continue from 6 and print numbers 6 through 10.
break
to exit a loop when the number 7 is found in a list of numbers.continue
to skip all even numbers in a loop from 1 to 20 and print only the odd numbers.break
in a loop without understanding its effectβit stops the entire loop!continue
with break
βcontinue
skips the current iteration but doesnβt stop the loop.Feel free to experiment with both break
and continue
in the examples. Try changing the conditions and observe the difference in the behavior of the loops!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!