CodeBlanks Logo Icon CodeBlanks

break and continue

Learn to exit a loop with break and skip with continue.

break and continue

break ends a loop early; continue skips the current iteration and moves to the next. Both change the loop flow.

for (int i = 0; i < 10; i++) {
    if (i == 5) break;
    if (i % 2 == 0) continue;
    printf("%d\n", i);
}

Here when i=5 the loop ends. Even i values are skipped with continue. Output: 1 3 (only odd and less than 5). These statements let you control loops flexibly.

break in switch

break is also used to exit a switch block. Outside loops it works in switch; it cannot exit if blocks.

switch (n) {
    case 1: printf("One"); break;
    case 2: printf("Two"); break;
    default: printf("Other");
}

Without break in each case, flow falls through to the next case. This is called fall-through; sometimes wanted, usually a bug.

Practice Exit early with break

Write a C program. Write a for (int i = 1; i <= 10; i++) loop. Exit at 5 with if (i == 5) break;. Print printf("%d\n", i); each iteration. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // for from 1 to 10, break at 5
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) break;
        printf("%d\n", i);
    }
    return 0;
}

Expected output

1
2
3
4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does continue do?

main.c
for (int i = 0; i < 5; i++) {
    if (i == 2) continue;
    printf("%d", i);
}
  • Ends the loop
  • Skips this iteration Correct answer
  • Raises an error
  • Stops the program

Explanation: continue skips this iteration and moves to the next.

2 Match break/continue

Term Meaning
break Ends the loop
continue Skips iteration
switch break Exits the case
if Control statement

3 End the loop

Question
for (int i = 0; i < 100; i++) {
    if (i == 10) ____;
    printf("%d", i);
}
Answer
for (int i = 0; i < 100; i++) {
    if (i == 10) break;
    printf("%d", i);
}

Explanation: break exits the loop early.

All lessons in Beginner