loops and decisions - weber state...

30
Loops and Decisions Chapter 3 Copyright © 1998-2004 Delroy A. Brinkerhoff. All Rights Reserved. CS 1410 Chapter 3 Slide 1 of 30

Upload: hadieu

Post on 09-Mar-2018

218 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Loops and DecisionsChapter 3

Copyright © 1998-2004 Delroy A. Brinkerhoff. All Rights Reserved.CS 1410 Chapter 3 Slide 1 of 30

Page 2: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Logical ExpressionsRelational and logical operators – result is boolean-valued

P== equal to counter == 0P != not equal to counter != 0P> greater than counter > 0P< less than counter < 0P>= greater than or equal to counter >= 0P<= less than or equal to counter <= 0P&& logical and 0 < i && i < 10P | | logical or i <= 0 || i >= 10P ! logical not ! done

E1 E2 E1 && E2

f f ff t ft f ft t t

E1 E2 E1 || E2

f f ff t tt f tt t t

E !Et ff t

CS 1410 Chapter 3 Slide 2 of 30

Page 3: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Flow of Control StatementsThree kinds

PSequentialPBranches (also known as decisions)< if< if-else< switch

PLoops (also known as iterative)< for< while< do-while

CS 1410 Chapter 3 Slide 3 of 30

Page 4: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Sequential StatementsAll statements are executed once, one after another

entry

exit

statement 1

statement 2

statement 3

statement n

entry

exit

statement 1

statement 2

statement 3

statement n

;

;

;

;;;

;

{

}CS 1410 Chapter 3 Slide 4 of 30

Page 5: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

if-StatementExecuted if true

Expression StatementTrue

False

if (expression)statement;

if (line33 < line34)line37 = line36 - line35;

if (income >= 1400 || interest > 750){ must_file++;

deductions = 1;adjusted_income = line37;

}CS 1410 Chapter 3 Slide 5 of 30

Page 6: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Short Circuit EvaluationToward Compact and Efficient Code

PE1 and E2 are boolean-valued expressionsP if (E1 && E2)< if E1 is false, the whole expression is false and E2 is not evaluated

P if (E1 || E2)< if E1 is true, the whole expression is true and E2 is not evaluated

if (n != 0 && 100 / n > min) if (n != 0)if (100 / n > min)

CS 1410 Chapter 3 Slide 6 of 30

Page 7: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

if-else StatementChoose One Statement

Entry

Exit

State-1 State-2

ExpressionTrue False

if (expression)statement-1;

elsestatement-2;

if (line18 > line19)tax_owed = line18;

elserefund = line19;

if (lineFlag)printf("%8d",lines);

CS 1410 Chapter 3 Slide 7 of 30

Page 8: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

True and FalseAn Existential Dilemma?

PAny expression may be interpreted as a boolean value< 0 is false< Non-0 is true

PThe result of a “boolean” expression is either 1 or 0PC++ defines type bool with possible values: true & false< Syntactic window-dressing for an int< true = 1< false = 0

if (n % 2)printf("n is odd\n");

elseprintf("n is even\n");

if (strcmp(s1, s2))printf("s1 & s2 differ\n");

elseprintf("s1 & s2 are equal\n");

CS 1410 Chapter 3 Slide 8 of 30

Page 9: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Nested Conditional StatementUnlimited Nesting Depth

Entry

Exit

True False

True False True False

Exp-1

Exp-2 Exp-3

State-1 State-2 State-3 State-4

if (expression-1)if (expression-2)

statement-1;else

statement-2;else

if (expression-3)statement-3;

elsestatement-4;

CS 1410 Chapter 3 Slide 9 of 30

Page 10: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

The Dangling else Problemelse attaches to the last if

if (expression-1)if (expression-2)

statement-1;else

statement-2;

if (expression-1){ if (expression-2)

statement-1;}else

statement-2;

ex 1 ex 2

stat 2

stat 1true

false

true

ex 1 ex 2

stat 2

stat 1true

false

true

false

false

CS 1410 Chapter 3 Slide 10 of 30

Page 11: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

if-else-if LadderSelects and Executes One Statement

if (expression-1)statement-1;

else if (expression-2)statement-2;

else if (expression-3)statement-3;

.

.

.else if (expression-m)

statement-m;else

statement-n

Expression 1

Expression 2

Expression 3

Expression m

Statement 1

Statement 2

Statement 3

Statement m

Statement n

false

false

false

true

true

true

true

false

CS 1410 Chapter 3 Slide 11 of 30

Page 12: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Ctype “Library”Character Identification and Mapping

PUsing ctype macros< Macros return 1 for true and 0 for false< isascii( ) is defined on all integer values; the rest are defined only for

integers representing characters, or EOF< #include <ctype.h>

P int isalpha(int c)P int isupper(int c)P int islower(int c)P int isdigit(int c)P int isxdigit(int c)P int isalnum(int c)P int isspace(int c)

P int ispunct(int c)P int isprint(int c)P int isgraph(int c)P int iscntrl(int c)P int isascii(int c)P int toupper(int c) /* function */P int tolower(int c) /* function */

CS 1410 Chapter 3 Slide 12 of 30

Page 13: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Conditional ExpressionsBased on the Conditional Operator ?:

P (expr 1) ? (expr 2) : (expr 3)< If expr 1 is true, expr 2 is the value of the

overall expression< If expr 1 is false, expr 3 is the value of the

overall expression< Parentheses are not syntactically required< Typically used because ? has a high

precedencePmax = (x > y) ? x : y;Pmin = (x < y) ? x : y;P index = (index+1 == size) ? 0 : ++index;

expr 1

returnexpr 2

returnexpr 3

true false

CS 1410 Chapter 3 Slide 13 of 30

Page 14: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

switch StatementConstant Integral Selection

switch(expression){ case const-1: statements-1;

break;case const-2: statements-2;

/* fall-through */case const-3:case const-4: statements-3;

break;case const-5: break;

...default: statements-m;

break;}

break

Statements

Statements

break

Statements

Statements

break

break

expr==const1yes

yes

yes

yes

yes

no

no

no

no

default ?

expr==const2

expr==const3

expr==const4

CS 1410 Chapter 3 Slide 14 of 30

Page 15: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

switch ExampleExcerpt from wc.c

/* counts characters, words, and lines in a file */

switch(c){ case '\n' : lines++; /* fall through */

case ' ' :case '\t' : inword = 0;

break;default : if (! inword) /* start word */

{ inword = 1;words++;

}break;

}CS 1410 Chapter 3 Slide 15 of 30

Page 16: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

for LoopInitialization-Text-Update

PTest at top< May not execute

PAny expression may be omittedPExpression 1 is the initializer< Executed only once

PExpression 2 is the loop test< Loops while expression 2 is true< Tested after expr 1< Tested after expr 3

PExpression 3 is the update

exp-2

Statement

true

false

expr-3

expr-1

for (expr-1; expr-2; expr-3)statement;

CS 1410 Chapter 3 Slide 16 of 30

Page 17: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

for-Loop ExamplesSimple Counting

int i, j;

for (i = 0; i < 10; i++)printf(”%d\n”, i); /* prints 0 - 9 */

for (i = 0; i < 10; i += 2)printf(”%d\n”, i); /* prints 0, 2, 4, 6, 8 */

for (i = 0, j = 0; i < 10 && j < 5; i += 2, j++) /* comma operator */printf(”%d\t%d\n”, i , j);

for (i = 79; i >= 0 && s[i] == ‘ ’; i--) /* empty statement */;

CS 1410 Chapter 3 Slide 17 of 30

Page 18: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

for-Loop VariationsNon-“Standard” Loops

for (;;) /* infinite loop */statements;

for (i = 0; s[i] == ‘ ’; i++) /* initializes i */statements;

for (; s[i] != ‘\t’; i++) /* empty init */statements;

List* L; /* non-integer */for (L = root->next; L != root; L = L->next) /* loop walks */

statements; /* a linked list */

CS 1410 Chapter 3 Slide 18 of 30

Page 19: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

C++ for-LoopsLoop counter variable scope

PC requires that loop counter variables be defined outside ofthe loop in the variable definition area

PC++ did away with the variable definition area (i.e., variablesmay be defined anywhere within a program)< Loop counter variables may be defined in a for-loop< for (int i = 0; i < 100; i++) cout << i << endl;

PLoop counter variable scope< Old style: from the point of definition to the end of the block< New style: only in the for-loop itself< Microsoft Visual C++ 6.0 continues to use the old style< Microsoft .NET (7.0 and newer) implements the new style

CS 1410 Chapter 3 Slide 19 of 30

Page 20: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

C++ for-Loop ExamplesThe changing scope definition

PSecond if – if (i >= 0)< okay in Microsoft and the

old style-- i still in scope< fails the new style-- i went

out of scope with the forPOkay in all-- i is defined

outside of loop and hasblock scope

PSecond for loop< okay in the new style--

second i is a new variable< fails Microsoft and old

style-- i is multiplly defined

for (int i = 0; i < 10; i++)cout << i << endl;

if (i >= 0)cout << "i is big\n";

for (int i = 0; i < 10; i++)cout << i << endl;

for (int i = 0; i < 10; i++)cout << i << endl;

int i;for (i = 0; i < 10; i++)

cout << i << endl;if (i >= 0)

cout << "i is big\n";

CS 1410 Chapter 3 Slide 20 of 30

Page 21: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

while LoopControlled repetition

PTest at the top< May not be executed

PLoops while expression is true Exp

Statement

true

false

while (expression)statement;

int n = 100;while (n > 0)

printf("%d\n", n--);

while ((c = getopt(argc, argv, "cwl")) != EOF) { ... }

while ((c = fgetc(fp)) != EOF) { ... }CS 1410 Chapter 3 Slide 21 of 30

Page 22: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

do-while LoopLess Common Loop

PTest at the bottom< Executed at least once

PLoops while expression is true< Opposite of Pascal’s repeat-until

PUseful when the test expression iseffected by a statement in the loop body

Exp

Statement

true

false

do{

statements;} while (expression);

CS 1410 Chapter 3 Slide 22 of 30

Page 23: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Compound Statement: while/switchExcerpt from wc.c

int c, charFlag = 0, wordFlag = 0, lineFlag = 0;

while ((c = getopt(argc, argv, "cwl")) != EOF)switch(c){ case 'c' : charFlag++;

break;case 'w' : wordFlag++;

break;case 'l' : lineFlag++;

break;case '?' : fprintf(stderr, "ERROR: unknown option\n");

break;}

CS 1410 Chapter 3 Slide 23 of 30

Page 24: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Loop InterruptionUsed to simplify program structure

Pbreak< Terminates the inner most loop (execution resumes with the

statement following the loop)Pcontinue< Skips remaining code in inner loop (from the continue statement to

the end of the loop)< starts next loop iteration

– for loops resume at the update followed by the test– do and do-while loops resume at the test

PUsually in an if-statement

CS 1410 Chapter 3 Slide 24 of 30

Page 25: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Loop Interruption ExamplesSome Common Idioms

for (avi = optind; avi < argc; avi++){ if ((fp = fopen(argv[avi], "r")) == NULL)

{ printf("ERROR: unable to open \"%s\" n", argv[avi]);continue;

}

for (;;) /* from qsort partition */{ while (a[++i] < v);

while (a[--j] > v);if (j <= i) /* loop until i and j cross */

break;temp = a[i]; a[i] = a[j]; a[j] = temp;

}CS 1410 Chapter 3 Slide 25 of 30

Page 26: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

The null-statementNot a syntax error

PUncomon but sometimes useful with for-loopsPNot so useful with other control statements

if (expression) ;

for (ex1, ex2, ex3) ;

for (ex1, ex2, ex3);

null statement

more clear

CS 1410 Chapter 3 Slide 26 of 30

Page 27: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

More library functions

Pexit(status)< Terminates program< Returns exit status (0 is okay, non-zero is error)

Pgetch() and getche()< Returns a character as soon as the key is pressed (do not need to

press the enter key)< conio.h header file< Non-ANSI functions (i.e., less portable than usual)< Available on Windows< Available in the Unix/Linux curses package

CS 1410 Chapter 3 Slide 27 of 30

Page 28: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Debugging Control StatementsWhere is your code going?

if (expression){

cout << “true” << endl;. . . .

}else{

cout << “false” << endl;. . . .

}

for (int = 0; i < exp; i++){

cout << “loop: ” << i << endl;. . . .

}

CS 1410 Chapter 3 Slide 28 of 30

Page 29: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

Understanding LoopsManually work a problem with tables

double a = 0.0;for (int i = 0; i < f(a); i++){

int x = ....;int y = ....;a = f(x + i * y);

}

a i x y x+i*y0.0 0 5 14 36.7836.78 1 19 8 95.03

CS 1410 Chapter 3 Slide 29 of 30

Page 30: Loops and Decisions - Weber State Universityicarus.cs.weber.edu/~dab/cs1410/slides/Chap03.pdfSequential Statements All statements are executed once, one after another entry exit statement

The goto StatementUnconditional Jump

PMust be used carefully< Can make “spaghetti” code if abused< Use in rare, limited situations

– Interrupting nested loops– Creating error handling code– Implementing state machines

PMay not jump into (i.e., goto)functions, loops, ifs, or switches

for (i = 0; i < 100; i++){ for (j = 0; j < 100; j++)

{...

if (error)goto done;

}}

done: ...;

CS 1410 Chapter 3 Slide 30 of 30