Progress: 8 of 16 topics50%

Break and Continue Statements in C

Loop control statements like break and continue give you precise control over loop execution in C programming. These statements are essential for creating efficient loops that can respond to specific conditions during execution.

When to Use Loop Control Statements

Loop control statements are particularly useful when you need to:

  • Exit a loop early when a specific condition is met
  • Skip certain iterations without terminating the entire loop
  • Implement more complex loop logic based on runtime conditions
  • Create more efficient code by avoiding unnecessary iterations

The break Statement

The break statement immediately terminates the innermost loop (or switch statement) that contains it, transferring control to the statement following the terminated structure.

How break Works in Loops

Loop Starts
Condition Check
(break condition)
Condition True
Execute break
Condition False
Continue Loop
Loop Body
Loop Ends

Using break in for Loops

Here's an example of using break to exit a loop when a specific value is found:

c
1#include <stdio.h>
2
3int main() {
4 int target = 5;
5
6 printf("Searching for %d in the range 1-10\n", target);
7
8 for (int i = 1; i <= 10; i++) {
9 printf("Checking number: %d\n", i);
10
11 if (i == target) {
12 printf("Target %d found!\n", i);
13 break; // Exit the loop when target is found
14 }
15 }
16
17 printf("Loop completed.\n");
18 return 0;
19}
20
21// Output:
22// Searching for 5 in the range 1-10
23// Checking number: 1
24// Checking number: 2
25// Checking number: 3
26// Checking number: 4
27// Checking number: 5
28// Target 5 found!
29// Loop completed.

In this example:

  • We start a loop that counts from 1 to 10
  • When the counter i equals our target (5), we execute the break statement
  • The loop terminates immediately, skipping the remaining iterations (6-10)
  • Control transfers to the statement after the loop body (printf("Loop completed.\\n"))

Using break in while and do-while Loops

The break statement works the same way in while and do-while loops:

c
1#include <stdio.h>
2
3int main() {
4 // break in a while loop
5 printf("\nbreak in a while loop:\n");
6 int num = 1;
7
8 while (num <= 10) {
9 printf("%d ", num);
10
11 if (num == 5) {
12 printf("\nBreaking the loop at %d\n", num);
13 break;
14 }
15
16 num++;
17 }
18
19 // break in a do-while loop
20 printf("\nbreak in a do-while loop:\n");
21 int counter = 1;
22
23 do {
24 printf("%d ", counter);
25
26 if (counter == 5) {
27 printf("\nBreaking the loop at %d\n", counter);
28 break;
29 }
30
31 counter++;
32 } while (counter <= 10);
33
34 return 0;
35}
36
37// Output:
38// break in a while loop:
39// 1 2 3 4 5
40// Breaking the loop at 5
41//
42// break in a do-while loop:
43// 1 2 3 4 5
44// Breaking the loop at 5

Breaking from Nested Loops

When using break in nested loops, it only terminates the innermost loop that contains it:

c
1#include <stdio.h>
2
3int main() {
4 printf("Nested Loops with break:\n");
5
6 for (int i = 1; i <= 3; i++) {
7 printf("Outer loop iteration %d: ", i);
8
9 for (int j = 1; j <= 5; j++) {
10 printf("%d ", j);
11
12 if (j == 3) {
13 printf("[break] ");
14 break; // This only breaks out of the inner loop
15 }
16 }
17
18 printf("Outer loop continues\n");
19 }
20
21 return 0;
22}
23
24// Output:
25// Nested Loops with break:
26// Outer loop iteration 1: 1 2 3 [break] Outer loop continues
27// Outer loop iteration 2: 1 2 3 [break] Outer loop continues
28// Outer loop iteration 3: 1 2 3 [break] Outer loop continues

Breaking from Multiple Nested Loops

Unlike some other languages, C doesn't have a direct way to break out of multiple nested loops at once. However, you can achieve this using one of these techniques:

  • Using a flag variable and checking it in each loop
  • Using goto (generally discouraged but can be appropriate in this specific case)
  • Refactoring the nested loops into a function and using return
c
// Example using a flag variable
#include <stdio.h>
int main() {
int done = 0; // Flag variable
for (int i = 1; i <= 3 && !done; i++) {
for (int j = 1; j <= 3 && !done; j++) {
printf("(%d,%d) ", i, j);
if (i == 2 && j == 2) {
printf("\nFound target! Breaking out of all loops\n");
done = 1; // Set the flag to exit both loops
}
}
printf("\n");
}
return 0;
}
// Output:
// (1,1) (1,2) (1,3)
// (2,1) (2,2)
// Found target! Breaking out of all loops

The continue Statement

The continue statement skips the remaining code in the current iteration of a loop and jumps to the next iteration. Unlike break, it doesn't terminate the loop.

How continue Works in Loops

Loop Starts
Loop Body (First Part)
Condition Check
(continue condition)
Condition True
Execute continue
Condition False
Loop Body (Rest)
Loop Ends

Using continue in for Loops

Here's an example of using continue to skip printing even numbers:

c
1#include <stdio.h>
2
3int main() {
4 printf("Printing only odd numbers from 1 to 10:\n");
5
6 for (int i = 1; i <= 10; i++) {
7 // Skip even numbers
8 if (i % 2 == 0) {
9 continue; // Skip the rest of this iteration
10 }
11
12 printf("%d ", i);
13 }
14 printf("\n");
15
16 return 0;
17}
18
19// Output:
20// Printing only odd numbers from 1 to 10:
21// 1 3 5 7 9

In this example:

  • We start a loop that counts from 1 to 10
  • For each number, we check if it's even (divisible by 2)
  • If the number is even, we execute continue, skipping to the next iteration
  • Only odd numbers proceed to the printf statement

Using continue in while and do-while Loops

When using continue in while and do-while loops, be careful with your loop control variables:

c
1#include <stdio.h>
2
3int main() {
4 // continue in a while loop
5 printf("\ncontinue in a while loop:\n");
6 int i = 0;
7
8 while (i < 10) {
9 i++; // IMPORTANT: Update the counter BEFORE the continue statement
10
11 if (i % 2 == 0) {
12 continue; // Skip even numbers
13 }
14
15 printf("%d ", i);
16 }
17 printf("\n");
18
19 // continue in a do-while loop
20 printf("\ncontinue in a do-while loop:\n");
21 int j = 0;
22
23 do {
24 j++; // IMPORTANT: Update the counter BEFORE the continue statement
25
26 if (j % 2 == 0) {
27 continue; // Skip even numbers
28 }
29
30 printf("%d ", j);
31 } while (j < 10);
32 printf("\n");
33
34 return 0;
35}
36
37// Output:
38// continue in a while loop:
39// 1 3 5 7 9
40//
41// continue in a do-while loop:
42// 1 3 5 7 9

⚠️ Common Pitfall with continue

When using continue in while and do-while loops, make sure to update your loop control variables before the continue statement. Otherwise, you might create an infinite loop:

c
// INCORRECT - Can cause infinite loop
while (i < 10) {
if (i % 2 == 0) {
continue; // If i is even, this will skip the i++ statement
}
printf("%d ", i);
i++; // This line never executes if i is even
}

Practical Applications

Example 1: Finding Prime Numbers

Using break to optimize prime number checking:

c
1#include <stdio.h>
2#include <stdbool.h>
3#include <math.h>
4
5bool isPrime(int num) {
6 // Handle special cases
7 if (num <= 1) return false;
8 if (num <= 3) return true;
9 if (num % 2 == 0 || num % 3 == 0) return false;
10
11 // Check for divisibility using the 6k±1 optimization
12 int limit = sqrt(num);
13 for (int i = 5; i <= limit; i += 6) {
14 if (num % i == 0 || num % (i + 2) == 0) {
15 return false; // Not a prime number
16 }
17 }
18
19 return true; // Is a prime number
20}
21
22int main() {
23 printf("Prime numbers between 1 and 50:\n");
24
25 for (int i = 1; i <= 50; i++) {
26 if (isPrime(i)) {
27 printf("%d ", i);
28 }
29 }
30 printf("\n");
31
32 return 0;
33}
34
35// Output:
36// Prime numbers between 1 and 50:
37// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Example 2: Processing Input with Validation

Using continue to handle invalid input:

c
1#include <stdio.h>
2
3int main() {
4 int numbers[5];
5 int count = 0;
6
7 printf("Enter 5 positive numbers:\n");
8
9 while (count < 5) {
10 int input;
11 printf("Enter number %d: ", count + 1);
12 scanf("%d", &input);
13
14 if (input <= 0) {
15 printf("Please enter a positive number!\n");
16 continue; // Skip this iteration and ask again
17 }
18
19 numbers[count] = input;
20 count++;
21 }
22
23 printf("\nYou entered: ");
24 for (int i = 0; i < 5; i++) {
25 printf("%d ", numbers[i]);
26 }
27 printf("\n");
28
29 return 0;
30}
31
32// Example Interaction:
33// Enter 5 positive numbers:
34// Enter number 1: 10
35// Enter number 2: -5
36// Please enter a positive number!
37// Enter number 2: 20
38// Enter number 3: 0
39// Please enter a positive number!
40// Enter number 3: 30
41// Enter number 4: 40
42// Enter number 5: 50
43//
44// You entered: 10 20 30 40 50

Example 3: Early Termination with break

Using break for efficiency in searching algorithms:

c
1#include <stdio.h>
2
3int main() {
4 int numbers[] = {10, 25, 33, 47, 52, 68, 71, 86, 92, 99};
5 int length = 10;
6 int searchValue = 52;
7 int position = -1;
8
9 printf("Searching for %d in the array:\n", searchValue);
10
11 for (int i = 0; i < length; i++) {
12 printf("Checking index %d (value: %d)\n", i, numbers[i]);
13
14 if (numbers[i] == searchValue) {
15 position = i;
16 printf("Found %d at index %d!\n", searchValue, position);
17 break; // No need to check the rest of the array
18 }
19 }
20
21 if (position == -1) {
22 printf("%d not found in the array.\n", searchValue);
23 }
24
25 return 0;
26}
27
28// Output:
29// Searching for 52 in the array:
30// Checking index 0 (value: 10)
31// Checking index 1 (value: 25)
32// Checking index 2 (value: 33)
33// Checking index 3 (value: 47)
34// Checking index 4 (value: 52)
35// Found 52 at index 4!

Using break in switch Statements

As we've seen in the Switch Statements tutorial,break is also commonly used in switch statements to prevent fall-through behavior:

c
1#include <stdio.h>
2
3int main() {
4 char grade = 'B';
5
6 switch (grade) {
7 case 'A':
8 printf("Excellent!\n");
9 break; // Without this, execution would continue to the next case
10
11 case 'B':
12 printf("Good job!\n");
13 break;
14
15 case 'C':
16 printf("Satisfactory.\n");
17 break;
18
19 default:
20 printf("Need improvement.\n");
21 }
22
23 return 0;
24}
25
26// Output:
27// Good job!

🎯 Try it yourself!

Practice using break and continue with these exercises:

  • Write a program that prints all numbers from 1 to 100, but skips multiples of both 3 and 5
  • Create a menu-driven program that uses break to exit when the user selects "Quit"
  • Implement a program that reads numbers until the user enters 0, then calculates their sum

Best Practices for Using break and continue

Do

  • Use break to exit a loop when further iterations are unnecessary
  • Use continue to skip iterations that don't need processing
  • Update loop control variables before continue in while/do-while loops
  • Add comments explaining why a break or continue is necessary
  • Consider using functions instead of deeply nested loops with breaks

Avoid

  • Overusing break and continue which can make code harder to read
  • Forgetting break statements in switch cases (unless fall-through is intended)
  • Using continue in a loop where loop variables are updated after it
  • Creating complex logic that relies heavily on multiple breaks
  • Using goto as a substitute for proper loop control (in most cases)

Summary

In this tutorial, you've learned:

  • How the break statement terminates loops and switch statements
  • How the continue statement skips the current iteration in a loop
  • How to use break to exit loops early when a condition is met
  • How to use continue to skip specific iterations
  • Common pitfalls and best practices when using these statements
  • Practical applications in real-world programming scenarios

Break and continue statements give you precise control over loop execution in C. Understanding when and how to use them properly can lead to more efficient and readable code. In the next tutorial, we'll explore Functions in C, which allow you to organize your code into reusable blocks.

Related Tutorials

Loops in C

Learn about different types of loops in C programming.

Continue learning

Switch Statements in C

Multi-way decision making in C with switch statements.

Continue learning

Functions in C

Learn how to create and use functions in C programming.

Continue learning