OverIQ.com

The break and continue statement in C

Last updated on July 27, 2020


break statement #

Suppose we are writing a program to search for a particular number among 1000 numbers. In the 10th iteration, we have found the desired number. At this point, we don't want to transverse the remaining 990 numbers instead we want the loop to terminate and continue with the execution of statement following the loop. This is where the break statement comes into the play.

When break statement is encountered within the loop, the program control immediately breaks out of the loop and resumes execution with the statement following the loop. The break statement is commonly used in conjunction with a condition.

Let's take an example:

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

int main()
{
    int i;

    for(i = 1; i < 10 ; i++)
    {
        if(i==5)
        {
            break; // breaks out of the for loop
        }
        printf("Value of i = %d\n", i);
    }

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

1
2
3
4
Value of i = 1
Value of i = 2
Value of i = 3
Value of i = 4

How it works:

In the 5th iteration value of i becomes 5. The condition (i==5) is checked since it is true. The break statement is executed and the control comes out the for loop to execute the statement following it. Had there been no break statement, this loop would have been executed 9 times.

Let's create something more useful. The following program determines whether the number entered by the user is prime or not.

 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
27
28
29
30
31
32
33
34
35
36
#include<stdio.h>

int main()
{
    int i, num, flag=1;

    printf("Enter a number: ");
    scanf("%d", &num);

    for(i = 2; i < num-1 ; i++)
    {
        /*
            when this condition becomes true,
            it means that entered number is
            divisible by a number between 2 and num-1.
            So it can't be prime.
        */
        if(num%i==0)
        {
            flag = 0; // number is not prime
        }
    }

    if(flag==1)
    {
        printf("%d is prime", num);
    }

    else
    {
        printf("%d is not prime prime", num);
    }

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

1st run:

1
2
Enter a number: 5
5 is prime

2nd run:

1
2
Enter a number: 6
6 is not prime

How it works:

A number is prime if it is only divisible by 1 and itself. Here is one way to test whether a number is prime or not. Try dividing the number from 2 to one less than the number, if it is found to be divisible by any number within that range, then it is not prime, otherwise it is a prime number.

After looping through all the numbers from 2 to n-1. If the value of the variable flag remains set to 1. Then the number n is prime, otherwise, it is not.

Let's say in the first run the user entered 5.

In for loop i is initialized to 2. The condition (i < num-1) or (2 < 4) is checked, since it is true, control moves ahead to execute the body of the loop. In the loop body, the if condition num%i == 0 i.e 5%2 == 0 is tested, since it is false. The statement in the body of the if is omitted. Then the value of i is incremented using i++. The condition (i < num-1) i.e 2 < 4 is checked again, since it is still true the body of the for is executed once more. The process repeats until i < num-1. Even after the third and fourth iteration the value of flag remains the same i.e 1. When control comes out of for loop, the if condition i.e flag==1 is checked, since it is true the statement inside the body of the if statement is executed.

Again, Let's say in the second run the user entered 6.

Everything works exactly as described above. Except in the 2nd iteration when i reaches 3, the if condition (num%i==0) i.e 6%3 == 0 is checked, since it is true. Control moves ahead to execute statement inside the body of the if block. Inside the if block the variable flag is initialized to 1, this means that the number is not prime. The break statement breaks out of the for loop. If condition outside the loop is tested again i.e flag==1, as it is false, the statement in the else block is executed.

The break Statement inside a Nested Loop #

When the break statement is used inside a nested loop then it causes exit only from the innermost loop.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<stdio.h>
int main()
{
    int i, j;

    for(i = 1; i < 5 ; i++)
    {
        printf("Outer for loop, i = %d\n", i);

        for(j = 1; j < 5 ; j++)
        {
            if(j==3)
            {
                 printf("Breaking out from the inner loop \n");  
                 break; // break out from inner loop only
            }
            printf("Inner for loop, j = %d\n", j);
        }
        printf("\n");
    }

    // signal to operating system program ran fine
    return 0;
}

Expected Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Outer for loop, i = 1
Inner for loop, j = 1
Inner for loop, j = 2
Breaking out from the inner loop

Outer for loop, i = 2
Inner for loop, j = 1
Inner for loop, j = 2
Breaking out from the inner loop

Outer for loop, i = 3
Inner for loop, j = 1
Inner for loop, j = 2
Breaking out from the inner loop

Outer for loop, i = 4
Inner for loop, j = 1
Inner for loop, j = 2
Breaking out from the inner loop

In this case, when the value of j reaches 3, the condition j == 3 is evaluated to true and break statement causes an exit from the inner for loop (the outer for loop will keep executing) and the program control is transferred to the statement following the loop.

continue statement #

The continue statement is used to prematurely end the current iteration and move on the to the next iteration. When the continue statement is encountered in a loop, all the statements after the continue statement are omitted and the loop continues with the next iteration. The continue statement is used in conjunction with a condition.

Sometimes people get confused with between the break and and continue statement. Always remember that the break statement when encountered breaks out of the loop, but when the continue statement is encountered, the loop is not terminated instead the control is passed to the beginning of the loop.

When the continue statement is encountered in the while and do while loop, the control is transferred to the test condition and then the loop continues. whereas in the for loop when continue statement is encountered the control is transferred to the update expression, then the condition is tested.

The following program prints all the numbers between 0 to 10 which are not divisible by 4 using the continue statement.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>

int main()
{
    int i;

    for(i = 0; i < 10; i++)
    {
        if( i % 4 == 0 )
        {
            /*
                when i is divisible by 4
                continue to the next iteration
            */
            continue;
        }
        printf("%d\n", i);
    }

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

text
1
2
3
5
6
7
9
`

How it works:

When the for loop starts the variable i is set to 0, then the condition (i < 10) or (0 < 10) is tested, since it is true, the program control moves ahead to execute the loop body. Inside the loop body, the if condition i % 4 == 0 i.e 0 % 4 == 0 is checked, since it is false, the execution of statement in the if body is skipped. In line 17, we print the value of i, using the printf() statement. There are no more statements to execute in the loop body, so the program control is transferred to the update expression (i++). This completes the first iteration.

In the 5th iteration, the value of i reaches 4. Then the if condition (i % 4 == 0) i.e (4 % 4 == 0) is tested, since it is true, the continue statement is executed, and the control is transferred to the update expression. The expression i++ increments the value of the variable i by 1. Then, the condition i < 10 is tested again. This process continues until i < 10.