Lecture12

advertisement
C Programming
Lecture 12
The Compound Statement
A compound statement is a
series of declarations and
statements surrounded by
braces.
 A compound statement is
itself a statement

• In C, wherever it is correct to
place a statement, you may also
place a compound statement.
Example of a
Compound Statement
{
}
int a = 1, sum = 0;
while (a <= 10)
{
sum = sum + a;
a = a + 1;
printf(“%d\n”, a);
}
printf(“%d\n”, sum);
/* Note there is a compound statement
within a compound statement. */
The Use of
Compound Statements
To group statements into an
executable unit.
 To achieve the desired flow
of control in if, if-else,
while, for, do, and switch
statements.

• We are about to study these
statements in greater detail.
The Empty Statement

The empty statement is
written as a single
semicolon.
• It is useful where a statement
is needed syntactically but no
action is required semantically.
Delay Loop with
Empty Statement
int i = 0;
. . .
printf(“Error: reenter data.\n”);
while (++i < 10000) /* delay */
;
system(“clear”);
. . .
/* while loop keeps message on */
/* the screen momentarily.
*/
The while Statement



General Form of while Statement
while (expr)
statement
next statement
First expr is evaluated. If it is
nonzero (true), then statement is
executed, and control is passed back to
the beginning of the while loop.
The body of the while loop, namely
statement, is executed repeatedly until
expr is zero (false). At that point
control passes to next statement.
Example of while Statement
int i = 1, sum = 0;
. . .
while (i <= 10) {
sum += i;
++i;
}
printf(“%d\n”, sum);
Number of times through loop Value of sum
first
1 (0 + 1)
second
3 (1 + 2)
third
6 (3 + 3)
The for Statement

General Form of the for Statement
for (expr1; expr2; expr3)
statement
next statement

First expr1 is evaluated; typically expr1 is
used to initialize the loop.
Then expr2 is evaluated; if it is nonzero
(true) then statement is executed, expr3 is
evaluated, and control passes back to the
beginning of the for loop again, except that
evaluation of expr1 is skipped. The process
continues until expr2 is zero (false), at which
point control passes to next statement.

Typical Roles of for Loop
expr1, expr2, & expr3




General Form of the for Statement
for (expr1; expr2; expr3)
statement
next statement
expr1 is used to initialize the loop.
expr2 is a logical expression
controlling the iteration. The loop
exits when expr2 becomes false.
expr3 typically modifies a variable in
expr2 eventually causing expr2 to
become false.
/* Printing Random Numbers */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, n;
i=0
printf(“\n%s\n%s”,
“Some randomly distributed integers will be printed.”,
“How many do you want to see? “);
scanf(“%d”, &n);
for (i = 0; i < n; ++i) {
while (i++ < n) {
if (i % 6 == 0)
...
printf(“\n”);
...
printf(“%9d”, rand());
...
}
}
printf(“\n”);
equivalent code
return 0;
using while
}
Equivalence of
for and while Loops
for (expr1; expr2; expr3)
statement
statement
Is Equivalent to:
expr1;
while (expr2) {
statement
expr3;
}
next statement
The for loop has the
advantage of keeping
both the control
(expr2) and the
indexing (expr3) all
in one place at the
top of the loop.
Missing Expressions
in the for Loop

Any or all of the expressions in a
for statement can be missing, but
the two semicolons must remain.
i = 1;
sum = 0;
for ( ; i <= 10; )
sum += i++;
printf(“%d\n”, sum);
}
Embedded for Statements


A for statement can be used as the
statement part of an if, if-else,
while, or another for statement.
See example “Combinatorics” on
page 108.
• Combinatorics involves combinations
and permutations. This program lists
all triples of nonnegative numbers
that add up to a given number N.
The Comma Operator

The comma operator has the
lowest precedence of any
operator in C.
• It is a binary operator that
associates from left to right.

General Form
expr1, expr2
Value and Type of the Comma Operator
The comma expression as a
whole has the value and type
of its right operand.
 Example:

a = 0, b = 1
If b has been declared as an int,
this expression has a value of 1
and a type of int.
Use of the comma Operator
in a for Statement


You can use the comma operator in a
for statement to do multiple
initializations and multiple
processing of indices.
Examples
for (sum = 0, i = 1; i <= n; ++i)
sum += i;
for (sum = 0, i = 1; i <= n; sum += i, ++i)
;
Example of comma Expressions
Declarations and Initializations
int
double
i, j, k = 3;
x = 3.3;
Expression:
Equiv Expression:
Value:
i = 1, j = 2, ++k + 1
((i = 1), (j = 2)), ((++k) + 1)
5
Expression:
Equiv Expression:
Value:
k != 7, ++ x * 2.0 + 1
(k != 7), (((++ x) * 2.0) + 1)
9.6
Use of Commas in Your Code

Most commas in programs do not
represent comma operators.
• Commas used to separate expressions
in argument lists of functions or
within initializer lists are not
comma operators.
• If a comma operator is to be used in
these places, the comma expression in
which it occurs must be enclosed
within parentheses.
The do Statement

The do statement is a variant of
the while statement that tests its
condition at the bottom of the
loop.
General Form of the do Statement
do
statement
while (expr);
next statement
Examples of a do Statement
do {
sum += i;
scanf(“%d”, &i);
} while (i > 0);
do {
printf(“Input feet: “);
scanf(“%d”, &feet);
if (feet > 2)
printf(“\nEnter a 1 or 2:\n\n”);
} while (feet > 2);
The goto Statement
goto causes an unconditional
jump to a labeled statement
somewhere in the current
function.
 Form of a labeled statement.

label: statement
Where label is an identifier.
Example of goto and label
while (scanf(“%lf”, &x) == 1) {
if (x < 0.0)
goto negative_alert;
printf(“%f
%f
%f”,
x, sqrt(x), sqrt(2 * x));
}
negative_alert:
if (x < 0.0)
printf(“Negative value encountered!\n”);
Same Example Without goto
while(scanf(“%lf”, &x) == 1 && x >= 0.0)
printf(“%f
%f
%f\n”,
x,
sqrt(x), sqrt(2 * x));
if (x < 0.0)
printf(“Negative value encountered!\n);
&& x >= 0.0 accomplishes what the goto
accomplished, namely the printf() will
not be executed if a negative number is
entered.
When Should goto Be Used?


Almost never (it is never
needed).
• gotos can make a program very
difficult to read and
understand.
In rare instances such as exiting
from a deeply nested inner loop to
the outermost level, a goto can
make a program execute with
significantly greater efficiency.
The break and continue Statements


The break statement causes an exit
from the innermost enclosing loop
or switch statement.
The continue statement causes the
current iteration of a loop to
stop and the next iteration to
begin immediately.
Example Using a break Statement
while (1) {
scanf(“%lf”, &x);
if (x < 0.0)
break;
printf(“%f\n”, sqrt(x));
}
/* break causes jump to next statement */
/* after the while loop.
*/
Example Using a continue Statement
while (cnt < n) {
scanf(“%lf”, &x);
if (x > -0.01 && x < +0.01)
continue;
/* disregard small values */
++cnt;
sum += x;
/* continue transfers control to */
/* here to immediately begin the */
/* next iteration.
*/
}
Download