Documente Academic
Documente Profesional
Documente Cultură
Programming
8 9
while Loop
General form
for loop (cont'd)
while (<condition>)
<stmt>
e.g.,
for ( ; ; ); /* Loop forever. */ repeats execution of stmt as long as con-
/* Copy stdin to stdout. */
dition evaluates to non-zero
for (int c; (c = getchar ()) != EOF; putchar (c));
/* Compute n! factorial. */ In fact, a for loop is expressible as a while
for (int i = n; n > 2; n--) i *= (n , 1); loop:
/* Walk through a linked list. */ <initialize>
for (List *p = head; p != 0; p = p->next) action (p); while (<exit test>)
f
<loop body>
<increment>
g
10 11
do while loop
while Loop (cont'd) General form:
e.g., do <stmt> while (<condition>);
while (1); /* Loop forever. */ Less commonly used than for or while
int c; loops.
while ((c = getchar ()) != EOF)
putchar (c);
Note that the exit test is at the bottom of
i = n; /* Compute n! factorial. */ the loop, this means that the loop always
while (n >= 0) executes at least once!
i *= --n;
int main (void) f
/* Walk through a linked list. */ const int MAX LEN = 80;
p = head; char name str[MAX LEN];
while (p != 0) f do f
action (p); cout << "enter name (\exit" to quit)";
p = p->next; cin.getline (name str, MAX LEN);
g process (name str);
g while (strcmp (name str, "exit") != 0);
return 0;
g
12 13
14 15
if Statement switch Statement
General form General form
if (<cond>) switch (<expr>) f <cases> g
<stmt1>
[else switch only works for scalar variables e.g.,
<stmt2>] integers, characters, enumerations.
Common mechanism for conditionally ex-
ecuting a statement sequence. Permits ecient selection from among a
set of values for a scalar variable.
#include <ctype.h>
char *character class (char c) f enum symbol type f
if (isalpha (c)) f CONST, SCALAR, STRING, RECORD, ARRAY
g symbol;
if (isupper (c)) /* */
switch (symbol) f
:::
return "is upper case"; case CONST: puts ( "constant"); /* FALLTHRU */
else case SCALAR: puts ( "scalar"); break;
return "is lower case"; case RECORD: puts ( "record"); break;
g default: puts ( "either array or string"); break;
else if (isdigit (c)) g
return "is a digit";
else if (isprint (c)) A break occurring inside a switch is sim-
return "is a printable char"; ilar to one occurring inside a looping con-
else
return "is an unprintable char"; struct.
g
16 17
23