Exiting Loops in C

In the previous lessons, we learned how to write iterative loops in C using the for, while, and do while statements. For for and while loops, we saw that we can exit the loop before the loop body if the control condition is no longer true. In the case of do while loops, we can exit immediately after the loop body if the control condition evaluates to false.

However, in real-world programming, there may be situations where we need to interrupt the current iteration of a loop, or exit the loop entirely, at an arbitrary point.

In the C programming language, the break and continue statements are used within loops to modify the normal flow of execution. The break statement allows you to exit immediately from the loop or control structure in which it appears, while the continue statement skips the current iteration and proceeds to the next one.

In this article, we will examine the use of these statements in detail and provide practical examples of how they can be used.

break Statement

We already saw in the lesson on the switch statement how the break statement can be used to transfer control flow out of a switch block.

Similarly, the break statement can be used to exit a for, while, or do loop.

Let’s analyze an example. Suppose we want to write a program that checks whether a number n is a prime number. One possible technique is to use a for loop that divides the variable n by every number between 2 and n-1. When, during the for loop, we find a number that divides n, there’s no need to continue iterating because we already know n is not a prime number. So we can exit the for loop early using the break statement.

Then, after the loop ends, we can use an if statement to check whether:

  • the loop terminated early — meaning n is not prime;
  • or the loop terminated normally — meaning n is prime.

We can implement the program like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* Check if an integer is a prime number */
#include <stdio.h>

int main() {
    int n;
    int d; /* divisor */

    printf("Enter a number to check: ");
    scanf("%d", &n);

    for (d = 2; d < n; ++d) {
        if (n % d == 0) {
            break;
        }
    }

    /* Final check */
    if (d < n) {
        printf("%d is not prime and is divisible by %d\n", n, d);
    }
    else {
        printf("%d is prime\n", n);
    }

    return 0;
}

If we compile and run the program above, we may get the following possible outputs:

Enter a number to check: 37
37 is prime
Enter a number to check: 56
56 is not prime and is divisible by 2

The break statement is also very useful when we need to exit loops from points other than the beginning or end. A typical example is loops that read user input and terminate when a specific value is entered.

Let’s consider another example. Suppose we want to write a program that asks the user to input a series of positive integers, and then calculates their sum. We can use a for loop that keeps reading numbers from standard input until the user enters zero:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/* Sum of integers */
#include <stdio.h>

int main() {
    int s, x;
    s = 0;
    for (;;) {
        printf("Enter a number (0 to exit): ");
        scanf("%d", &x);
        if (x == 0)
            break;
        s += x;
    }

    printf("The sum of the entered numbers is: %d\n", s);

    return 0;
}

Compiling and running the program might result in the following output:

Enter a number (0 to exit): 1
Enter a number (0 to exit): 2
Enter a number (0 to exit): 3
Enter a number (0 to exit): 4
Enter a number (0 to exit): 5
Enter a number (0 to exit): 6
Enter a number (0 to exit): 7
Enter a number (0 to exit): 8
Enter a number (0 to exit): 9
Enter a number (0 to exit): 0
The sum of the entered numbers is: 45

As you can see, the program uses an infinite for loop on line 7. This loop asks the user for input and adds it to the variable s at each iteration. The loop continues indefinitely until the user enters 0. At that point, on line 11, the break statement is executed and the loop is exited.

Another important characteristic of the break statement to keep in mind is that it exits only the innermost loop. For example, if we have nested loops like this:

while ( ... ) {
    for ( ... ) {
        ...
        break;
        ...
    }
}

The break statement here exits the for loop and returns control to the outer while loop. In short, the break statement exits the loop or switch block in which it appears.

Definition

break Statement

The break statement in C is used to interrupt any loop—be it for, while, or do while—and return control to the statement immediately following the loop.

The break statement can also be used to exit a switch construct.

continue Statement

The continue statement behaves similarly to the break statement in that it ends the current iteration of the loop. The difference is that the break statement transfers control to the point immediately after the loop ends, while the continue statement transfers control to the point just before the end of the loop.

In other words, break exits the loop, while continue keeps control within the loop and moves to the next iteration.

The second difference is that break can be used inside a switch statement. The continue statement cannot be used within a switch; its use is limited to loops only.

Definition

continue Statement

The continue statement in C is used to interrupt the current iteration of a loop. When a continue statement is reached, the current iteration ends and control moves to the next iteration if the loop's control condition is still satisfied.

Let’s look at an example. Suppose we want to modify the program that sums positive integers entered by the user. Rather than summing an arbitrary number of values and stopping when 0 is entered, we modify the program so that it sums exactly 10 numbers. However, this time we skip summing numbers that are negative or equal to zero:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/* Sum of 10 integers */
#include <stdio.h>

int main() {
    int s, x, i;
    s = 0;
    while (i < 10) {
        printf("Enter addend %d: ", i + 1);
        scanf("%d", &x);
        if (x <= 0)
            continue;
        s += x;
        ++i;
    }

    printf("The sum of the 10 entered numbers is: %d\n", s);

    return 0;
}

If we compile and run the program, a possible output could be:

Enter addend 1: 10
Enter addend 2: 20
Enter addend 3: 30
Enter addend 4: 40
Enter addend 5: 50
Enter addend 6: 60
Enter addend 7: 70
Enter addend 8: 80
Enter addend 9: 90
Enter addend 10: 100
The sum of the 10 entered numbers is: 550

If we try entering negative numbers, this is what happens:

Enter addend 1: 0
Enter addend 1: -1
Enter addend 1: 0
Enter addend 1: 0
Enter addend 1: 1
Enter addend 2: 2
Enter addend 3: 3
...

By entering negative numbers or zeros, the continue statement on line 11 ends the current iteration and moves to the next one. Lines 12 and 13 are skipped, so the variable i is not incremented and the value of s remains unchanged.

Summary

In this lesson, we studied two important C language statements:

  • break: which ends any loop and transfers control to the first statement after the loop;
  • continue: which ends the current iteration of a loop and transfers control to the next iteration.

With these two statements, you can control the behavior of any loop in the C language.