Advanced Program Control 311
13
15: if (s[count] == ‘.’)
16: {
17: s[count+1] = ‘\0’;
18: break;
19: }
20: }
21: printf(“\nModified string: %s\n”, s);
22:
23: return 0;
24: }
Original string: This is a test string. It contains two sentences.
Modified string: This is a test string.
This program extracts the first sentence from a string. It searches the string, char-
acter by character, for the first period (which should mark the end of a sentence).
This is done in the forloop in lines 13 through 20. Line 13 starts the forloop, incre-
mentingcountto go from character to character in the string,s. Line 15 checks whether
the current character in the string is a period. If it is, a null character is inserted immedi-
ately after the period (line 17). This, in effect, trims the string. After you trim the string,
you no longer need to continue the loop, so a breakstatement in line 18 quickly termi-
nates the loop and sends control to the first line after the loop (line 21). If no period is
found, the string isn’t altered.
A loop can contain multiple breakstatements, but only the first breakexecuted (if any)
has any effect. If no breakis executed, the loop terminates normally (according to its test
condition). Figure 13.1 shows the operation of the breakstatement.
LISTING13.1 continued
OUTPUT
ANALYSIS
FIGURE13.1
The operation of the
breakandcontinue
statements.
while (... )
{
...
continue;
...
break;
...
...
}
21 448201x-CH13 8/13/02 11:12 AM Page 311