c programming lecture 12. the compound statement b a compound statement is a series of declarations...

28
C Programming C Programming Lecture 12 Lecture 12

Upload: margaretmargaret-atkinson

Post on 24-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

C ProgrammingC Programming

Lecture 12Lecture 12

Page 2: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The Compound The Compound StatementStatement

A A compound statementcompound statement is a is a series of series of declarationsdeclarations and and statementsstatements surrounded by surrounded by bracesbraces..

A compound statement is A compound statement is itself a statementitself a statement• In C, wherever it is correct to In C, wherever it is correct to place a statement, you may also place a statement, you may also place a compound statement.place a compound statement.

Page 3: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Example of a Example of a Compound StatementCompound Statement

{{ int a = 1, sum = 0;int a = 1, sum = 0; while (a <= 10)while (a <= 10) {{ sum = sum + a;sum = sum + a; a = a + 1;a = a + 1; printf(“%d\n”, a);printf(“%d\n”, a); }} printf(“%d\n”, sum);printf(“%d\n”, sum);}}/*/* Note Note there is a compound statement within a there is a compound statement within a compound statement. */ compound statement. */

Page 4: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The Use of The Use of Compound StatementsCompound Statements

To group statements into an To group statements into an executable unit.executable unit.

To achieve the desired flow To achieve the desired flow of control in of control in ifif, , if-elseif-else, , whilewhile, , forfor, , dodo, and , and switchswitch statements.statements.• We are about to study these We are about to study these statements in greater detail.statements in greater detail.

Page 5: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The Empty StatementThe Empty Statement

The The empty statementempty statement is is written as a written as a single single semicolonsemicolon..• It is useful where a statement It is useful where a statement is needed is needed syntacticallysyntactically but no but no action is required action is required semanticallysemantically..

Page 6: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Delay Loop withDelay Loop withEmpty StatementEmpty Statement

int i = 0;int i = 0; . . .. . . printf(“Error: reenter data.\n”);printf(“Error: reenter data.\n”); while (++i < 10000) while (++i < 10000) /* delay *//* delay */ ;; system(“clear”);system(“clear”); . . .. . . /* while loop keeps message on *//* while loop keeps message on */ /* the screen momentarily. *//* the screen momentarily. */

Page 7: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The while StatementThe while Statement General Form of General Form of whilewhile Statement Statement whilewhile ((exprexpr)) statementstatement next statementnext statement First First exprexpr is evaluated. is evaluated. If it is If it is nonzero (true),nonzero (true), then statement is then statement is executed, and control is passed back to executed, and control is passed back to the beginning of the while loop.the beginning of the while loop.

The The bodybody of the while loop, namely of the while loop, namely statementstatement, is executed repeatedly , is executed repeatedly untiluntil exprexpr is is zero (false).zero (false). At that point At that point control passes to control passes to next statementnext statement..

Page 8: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Example of while Example of while StatementStatement

int i = 1, sum = 0;int i = 1, sum = 0; . . .. . . while (i <= 10) {while (i <= 10) { sum += i;sum += i; ++i;++i; }} printf(“%d\n”, sum);printf(“%d\n”, sum);

Number of times through loop Value of sum first 1 (0 + 1) second 3 (1 + 2) third 6 (3 + 3)

Page 9: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The for StatementThe for Statement General Form of the for StatementGeneral Form of the for Statement forfor ((expr1expr1; ; expr2expr2; ; expr3expr3)) statementstatement next statement next statement First First expr1expr1 is evaluated; typically expr1 is is evaluated; typically expr1 is

used to initialize the loop.used to initialize the loop. Then Then expr2expr2 is evaluated; if it is nonzero is evaluated; if it is nonzero

(true) then statement is executed, (true) then statement is executed, expr3expr3 is is evaluated, and control passes back to the evaluated, and control passes back to the beginning of the for loop again, except that beginning of the for loop again, except that evaluation of evaluation of expr1expr1 is skipped. The process is skipped. The process continues until continues until expr2expr2 is zero (false), at which is zero (false), at which point control passes to point control passes to next statementnext statement..

Page 10: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Typical Roles of Typical Roles of forfor Loop Loopexpr1, expr2, & expr3expr1, expr2, & expr3

General Form of the for StatementGeneral Form of the for Statement forfor ((expr1expr1; ; expr2expr2; ; expr3expr3)) statementstatement next statement next statement expr1expr1 is used to initialize the loop. is used to initialize the loop. expr2expr2 is a logical expression is a logical expression controlling the iteration. The loop controlling the iteration. The loop exits when exits when expr2expr2 becomes false. becomes false.

expr3expr3 typically modifies a variable in typically modifies a variable in expr2expr2 eventually causing eventually causing expr2expr2 to to become false.become false.

Page 11: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

/* 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}

Page 12: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Equivalence of Equivalence of for and while Loopsfor and while Loops

for (for (expr1expr1; ; expr2expr2; ; expr3expr3)) statementstatementstatementstatement

Is Equivalent to:Is Equivalent to: The The forfor loop has the loop has the expr1expr1; ; advantage of keepingadvantage of keepingwhilewhile ((expr2expr2)) { { both the both the controlcontrol statement statement ((expr2expr2) and the) and the expr3expr3; ; indexingindexing ( (expr3expr3) all) all } } in one place at thein one place at thenext statement next statement top of the loop.top of the loop.

Page 13: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Missing Expressions Missing Expressions in the for Loopin the for Loop

Any or all of the expressions in a Any or all of the expressions in a forfor statement can be missing, but statement can be missing, but the two semicolons must remainthe two semicolons must remain..

i = 1;i = 1; sum = 0;sum = 0; for ( for ( ; ; i <= 10i <= 10;; ) ) sum += i++;sum += i++; printf(“%d\n”, sum);printf(“%d\n”, sum); }}

Page 14: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Embedded for StatementsEmbedded for Statements

A A forfor statement can be used as statement can be used as the statement partthe statement part of an of an ifif, , if-if-elseelse, , whilewhile, or , or another foranother for statement.statement.

See example “Combinatorics” on See example “Combinatorics” on page 108.page 108.• Combinatorics involves combinations Combinatorics involves combinations and permutations. This program lists and permutations. This program lists all triples of nonnegative numbers all triples of nonnegative numbers that add up to a given number N. that add up to a given number N.

Page 15: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The Comma OperatorThe Comma Operator

The comma operator has the The comma operator has the lowest precedence of any lowest precedence of any operator in C.operator in C.• It is a binary operator that It is a binary operator that associates from left to right.associates from left to right.

General FormGeneral Formexpr1, expr2expr1, expr2

Page 16: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Value and Type of the Comma Value and Type of the Comma OperatorOperator

The The comma expressioncomma expression as a as a whole has the whole has the valuevalue and and typetype of its of its right operandright operand..

Example:Example: a = 0, b = 1a = 0, b = 1

If If bb has been declared as an has been declared as an intint, , this this expressionexpression has a has a value of 1value of 1 and a and a type of inttype of int..

Page 17: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Use of the comma Use of the comma Operator Operator

in ain a for for Statement Statement

You can use the You can use the comma operatorcomma operator in a in a forfor statement to do statement to do multiple multiple initializationsinitializations and and multiple multiple processing of indicesprocessing of indices..

ExamplesExamplesfor (for (sum = 0sum = 0,, i = 1 i = 1; i <= n; ++i); i <= n; ++i)sum += i;sum += i;

for (for (sum = 0sum = 0,, i = 1 i = 1; i <= n; ; i <= n; sum += isum += i,, ++i ++i)); ;

Page 18: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Example of comma Example of comma ExpressionsExpressions

Declarations and Initializations

int i, j, k = 3;double x = 3.3;

Expression: i = 1, j = 2, ++k + 1Equiv Expression: ((i = 1), (j = 2)), ((++k) + 1) Value: 5

Expression: k != 7, ++ x * 2.0 + 1Equiv Expression: (k != 7), (((++ x) * 2.0) + 1)

Value: 9.6

Page 19: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Use of Commas in Your Use of Commas in Your CodeCode

Most commas in programs do not Most commas in programs do not represent comma operators.represent comma operators.• Commas used to separate expressions Commas used to separate expressions in argument lists of functions or in argument lists of functions or within initializer lists within initializer lists are notare not comma operators.comma operators.

• If a comma operator is to be used in If a comma operator is to be used in these places, the comma expression in these places, the comma expression in which it occurs which it occurs must be enclosed must be enclosed within parentheseswithin parentheses..

Page 20: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The The dodo Statement Statement

The The dodo statement is a statement is a variant ofvariant of the the whilewhile statement that tests statement that tests its condition at the its condition at the bottombottom of of the loop.the loop.

General Form of the do StatementGeneral Form of the do Statementdodostatementstatement

whilewhile ((exprexpr););next statementnext statement

Page 21: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Examples of a Examples of a dodo StatementStatement

dodo {{ sum += i;sum += i;

scanf(“%d”, &i);scanf(“%d”, &i);}} whilewhile ((i > 0i > 0););

do {do { printf(“Input feet: “);printf(“Input feet: “); scanf(“%d”, &feet);scanf(“%d”, &feet); if (feet > 2)if (feet > 2) printf(“\nEnter a 1 or 2:\n\n”);printf(“\nEnter a 1 or 2:\n\n”);} while (} while (feet > 2feet > 2););

Page 22: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The The gotogoto Statement Statement

gotogoto causes an causes an unconditional unconditional jumpjump to a to a labeled statementlabeled statement somewhere in the somewhere in the current current functionfunction..

Form of a labeled statement.Form of a labeled statement.label: statementlabel: statement

Where Where labellabel is an is an identifieridentifier..

Page 23: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Example of Example of gotogoto and and labellabel

while (scanf(“%lf”, &x) == 1) {while (scanf(“%lf”, &x) == 1) { if (x < 0.0)if (x < 0.0) gotogoto negative_alertnegative_alert;; printf(“%f %f %f”,printf(“%f %f %f”, x, sqrt(x), sqrt(2 * x));x, sqrt(x), sqrt(2 * x));}}

negative_alertnegative_alert::if (x < 0.0)if (x < 0.0) printf(“Negative value encountered!\n”); printf(“Negative value encountered!\n”);

Page 24: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Same Example Without Same Example Without gotogoto

while(scanf(“%lf”, &x) == 1 while(scanf(“%lf”, &x) == 1 && x >= 0.0&& x >= 0.0)) printf(“%f %f %f\n”,printf(“%f %f %f\n”, x, sqrt(x), sqrt(2 * x));x, sqrt(x), sqrt(2 * x));if (x < 0.0)if (x < 0.0) printf(“Negative value encountered!\n);printf(“Negative value encountered!\n);

&& x >= 0.0&& x >= 0.0 accomplishes what the goto accomplishes what the goto accomplished, namely the printf() will accomplished, namely the printf() will not be executed if a negative number is not be executed if a negative number is entered.entered.

Page 25: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

When Should When Should gotogoto Be Be Used?Used?

Almost Almost nevernever (it is (it is never never neededneeded).).• gotos can make a program very gotos can make a program very difficult to read and difficult to read and understand.understand.

In In rare instancesrare instances such as exiting such as exiting from a deeply nested inner loop from a deeply nested inner loop to the outermost level, a to the outermost level, a gotogoto can make a program execute with can make a program execute with significantly greater efficiency.significantly greater efficiency.

Page 26: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

The The breakbreak and and continuecontinue StatementsStatements

The The breakbreak statement causes an statement causes an exitexit from the from the innermostinnermost enclosing enclosing looploop or or switchswitch statement. statement.

The The continuecontinue statement causes the statement causes the current iterationcurrent iteration of a of a looploop to to stopstop and the and the next iteration to next iteration to begin immediatelybegin immediately..

Page 27: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Example Using a Example Using a breakbreak StatementStatement

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. */

Page 28: C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound

Example Using a Example Using a continuecontinue StatementStatement

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. */ }