UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

break and continue statements

break and continue statements alter the normal flow of control. Some programmers feel that these statements violate the norms of structured programming so they only use break in a switch structure and never use continue.

The break statement

The break statement, when executed in one of the repetition structures (for, while or do/while), causes immediate exit from the structure. Execution continues with the first statement after the loop.

while loop with a break statement

/* * File: addlist.c * --------------- * This program adds a list of numbers. The end of the * input is indicated by entering 0 as a sentinel value. */ #include <stdio.h> main() { int value, total; /* Give instructions to the user */ printf("This program adds a list of numbers.\n"); printf("Signal end of list with a 0.\n"); /* Initialize total */ total = 0; /* Get integers from the user until a 0 is entered, keeping a running total */ while (1) { printf("Enter an integer, 0 to end : "); scanf ("%d", &value); if (value == 0) { break; } total += value; } /* Print the total */ printf("The total is %d\n", total); }

Output

lassie% cc addlist.c lassie% lassie% a.out This program adds a list of numbers. Signal end of list with a 0. Enter an integer, 0 to end : 89 Enter an integer, 0 to end : 72 Enter an integer, 0 to end : 3 Enter an integer, 0 to end : 4 Enter an integer, 0 to end : 10 Enter an integer, 0 to end : 123 Enter an integer, 0 to end : 0 The total is 301 lassie%


The continue statement

The continue statement, when executed in one of the repetition structures (for, while or do/while), causes the remaining statements in the body of the loop to be skipped and the loop to start its next iteration.

example using a continue statement

/* * File: even.c * --------------- * This program prints the even numbers from 1 to 10. It * illustrates the continue statement, but is not * considered to be good code. */ #include <stdio.h> main() { int num; /* Give instructions to the user */ printf("This program prints even numbers\n"); printf("between 1 and 10.\n\n"); /* count from 1 to 10 */ for (num = 1; num <= 10; num++) { /* skip printing odd numbers */ if (num % 2 != 0) { continue; } /* will only print even numbers */ printf("%d ", num); } printf("\n"); }

Output

lassie% cc even.c lassie% lassie% a.out This program prints even numbers between 1 and 10. 2 4 6 8 10 lassie%


CSEE | 201 | 201 F'98 | lectures | news | help

Wednesday, 16-Sep-1998 18:17:31 EDT