A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
break exits the innermost enclosing loop or switch. continue skips the rest of the current iteration and jumps to the next condition check. Both are control-flow shortcuts. Used sparingly, they make code clearer. Used liberally, they turn a loop into spaghetti with extra steps. The rule I follow: if I need more than one break or continue in a single loop body, the loop is doing too much and should be split.
#include <stdio.h>int main(void) {int arr[] = {4, 17, 23, 8, 42, 15, 99};int n = 7;int target = 42;int found_index = -1;for (int i = 0; i < n; i++) {if (arr[i] == target) {found_index = i;break;}}if (found_index != -1) {printf("Found %d at index %d\n", target, found_index);} else {printf("%d not in array\n", target);}return 0;}
Without break, the loop would keep scanning indices 5 and 6 even after finding the target. Wasted cycles. In a linear search this is minor. In a loop processing millions of records or waiting on I/O, early exit is the difference between responsive and sluggish.
continue is the anti-nesting tool. Instead of wrapping the entire loop body in an if block, you guard-clause the unwanted cases and continue past them. The remaining code sits at the top indentation level, which makes it easier to read.
#include <stdio.h>int main(void) {printf("Odd numbers from 1 to 20:\n");for (int i = 1; i <= 20; i++) {if (i % 2 == 0) {continue;}printf("%d ", i);}printf("\n");return 0;}
This catches people off guard. A break inside an inner loop exits the inner loop only. The outer loop continues. If you need to break out of multiple levels, you either use a flag variable, a goto (yes, goto has legitimate uses), or restructure into a function and return.
#include <stdio.h>int main(void) {int matrix[3][3] = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};int target = 6;int found = 0;for (int row = 0; row < 3 && !found; row++) {for (int col = 0; col < 3; col++) {if (matrix[row][col] == target) {printf("Found %d at [%d][%d]\n", target, row, col);found = 1;break;}}}return 0;}
The found flag in the outer loop condition is the clean pattern. The break exits the inner loop, and the outer loop's condition check sees found is true and stops. No goto needed. No label gymnastics. Just a boolean and a compound condition.
Control flow is done. You can now branch, loop, exit early, and skip iterations. That covers every path your program can take. Next module: functions, where we package logic into reusable units and confront the question of what happens to variables when a function returns.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.