Sams Teach Yourself C in 21 Days

(singke) #1
statement2;
else if (condition3)
statement3;
else
statement4;

whileanddo...while..................................................................................

Thewhileanddo...whilestructures execute a statement repeatedly as long as a speci-
fied condition is true. The syntax for whileis:
while (condition)
statement;
The syntax for do...whileis as follows:
do
statement;
while (condition)
The main difference between these two structures is that whilechecksconditionfirst,
before executing the statement(s), so that if conditionis initially false, the statements
will not be executed at all. In contrast,do...whiledoes not check conditionuntil the
statement(s) have been executed once, so you are guaranteed at least one execution. As
you can see, both of these statements are like their C counterparts.

switch............................................................................................................

You use the switchconstruct to compare an expression against several test values, exe-
cuting the code that is associated with the matching value. The syntax is
switch (expression) {
case test1:
statementblock1;
case test2:
statementblock2;
case test3:
statementblock3;
default:
statementblock4;
}
Ifexpressionequalstest1,statement1is executed, and so on. If there is no match, the
statement following the defaultkeyword is executed. The defaultkeyword is optional.
If omitted, and there is no match, none of the statements in the switchconstruct are exe-
cuted. If there is more than one match, only the first one matters. Note that each state-
ment block in a switchconstruct should end with a breakstatement to prevent execution
from “falling through” to the next section. Here’s an example of switch:

718 Bonus Day 4

39 448201x-Bonus4 8/13/02 11:19 AM Page 718

Free download pdf