Submitted by tushar pramanick on Fri, 03/08/2013 - 00:19

The continue Statement

Instead of breaking a loop, there are times when you want to stay in a loop but skip over some statements within the loop. To do this, you can use the continue statement provided by C. The continue statement causes execution to jump to the top of the loop immediately.

You should be aware that using the continue statement, as well as the break statement, may make your program hard to debug.

For example, Listing 10.7 demonstrates how to use the continue statement in a loop doing sums.

TYPE
Listing 10.7. Using the continue statement.


1:  /* 10L07.c: Using the continue statement */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     int i, sum;
7:
8:     sum = 0;
9:     for (i=1; i<8; i++){
10:       if ((i==3) || (i==5))
11:          continue;
12:       sum += i;
13:    }
14:    printf("The sum of 1, 2, 4, 6, and 7 is: %d\n", sum);
15:    return 0;
16: }


    OUTPUT
    After the executable file 10L07.exe is run from a DOS prompt, the output is shown on the screen:

    C:\app>10L07
    The sum of 1, 2, 4, 6, and 7 is: 20
    C:\app>

    ANALYSIS
    In Listing 10.7, we want to calculate the sum of the integer values of 1, 2, 4, 6, and 7. Because the integers are almost consecutive, a for loop is built in lines 9_13. The statement in line 12 sums all consecutive integers from 1 to 7 (except for 3 and 5, which aren't in the listing and are skipped in the for loop).

By doing so, the expression (i==3) || (i==5) is evaluated in the if statement of line 10. If the expression returns 1 (that is, the value of i is equal to either 3 or 5), the continue statement in line 11 is executed, which causes the sum operation in line 12 to be skipped, and another iteration to be started at the beginning of the for loop. In this way, we obtain the sum of the integer values of 1, 2, 4, 6, and 7, but skip 3 and 5, automatically by using one for loop.

After the for loop, the value of sum, 20, is displayed on the screen by the printf() function in the statement of line 14.

Related Items

The exit() Function in C Programming

The exit() Function

There is also a C library function, exit(), that can be used to cause a program to end. Because the exit() function is defined in a header file, stdlib.h, you have to include the header file at the beginning of your program।

The void Data Type in C Programming

The void Data Type

You may notice that the void word has been added into the C program in Listing 2.2. void is a keyword for a data type in C. When a void is placed prior to a function name, it indicates that the function does not return a value.

#include Directive and Header Files in C Programming

The #include Directive
Let's now move to line 2 in the C program of Listing 2.1:

Compiling and Linking C Programs

Compiling and Linking

Debugging C Program

Debugging Your Program