chapter 9 structured programming using control flow...

59
© Christian Jacob Chapter Overview Chapter 9 Structured Programming Using Control Flow Commands 9.1 Statements for Decision and Control 9.2 Conditionals — “Decisions, Decisions, ...” 9.2.1 The if and if-else Statement 9.2.2 Truth Values in C++ 9.2.3 Nested if Statements 9.2.4 Short-Circuit Evaluation 9.2.5 The if-else-if Ladder 9.2.6 The switch Statement 9.2.7 Nested switch Statements

Upload: others

Post on 19-Oct-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

©

Christian Jacob

ds

Chapter Overview

Chapter 9

Structured ProgrammingUsing Control Flow Comman

9.1 Statements for Decision and Control

9.2 Conditionals — “Decisions, Decisions, ...”

9.2.1 The if and if-else Statement

9.2.2 Truth Values in C++

9.2.3 Nested

if

Statements

9.2.4 Short-Circuit Evaluation

9.2.5 The if-else-if Ladder

9.2.6 The switch Statement

9.2.7 Nested switch Statements

Page 2: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

© Christian Jacob

n ...”

nt

Chapter Overview

9.3 Loops — “Doing Things Over and Over Agai

9.3.1 An Abstract View of Loops

9.3.2 Three General Loop Patterns

9.3.3 The for Loop — Fixed Repetition

9.3.4 Variations on the for Loop

9.3.5 The while Loop — Pretest

9.3.6 The do-while Loop — A Post-Test Loop

9.3.7 Infinite Loops

9.4 Break and Continue

9.4.1 Using break to Exit Loops

9.4.2 Using continue

9.5 Using

goto

— “Spaghetti Programming”

9.6 Guidelines for Loops

9.6.1 How to Design Loops

9.6.2 Guidelines for Choosing a Looping Stateme

9.7 References

Page 3: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 3 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ontrol

First Back TOC

9.1 Statements for Decision and C

• Conditionals and Selection:

- if-then

- if-then-else

- switch

Loops

:

-

for

loop

-

while

loop

-

do-while

loop

Continue

and

break

Goto

Page 4: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 4 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

cisions, ...”

atement

atement

First Back TOC Conditionals — “Decisions, Decisions, ...”

9.2 Conditionals — “Decisions, De

9.2.1 The if and

if-else

Statement

• A single target statement:

if (

conditional_expression

)

st

• A single target statement:

if (

conditional_expression

)

st

else

statement

Page 5: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 5 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

nts:

nts:

First Back TOC Conditionals — “Decisions, Decisions, ...”

• Binary conditional with a sequence of stateme

if (conditional_expression){

statement_sequence

}

• Binary conditional with a sequence of stateme

if (

conditional_expression

){

statement_sequence

}else{

statement_sequence

}

Page 6: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 6 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ment2

First Back TOC Conditionals — “Decisions, Decisions, ...”

Behaviour diagram for conditional statements

statement1

state

conditionalexpression

true false

Page 7: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 7 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

r

the second

“;

\n’;by zero.\n”;

First Back TOC Conditionals — “Decisions, Decisions, ...”

Example (1): Division with Check for Zero Divide

// Divide the first number by

#include <iostream.h>

void main(){

int a, b;

cout << “Enter two numbers: cin >> a >> b;

if (b != 0) cout << a/b << ‘else cout << “Cannot divide

}

Page 8: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 8

Chapter 9: Structured Programming with Control Structures

©

Christian Jacob

Prev Next Last

f boolean

1

truth

s are:

First Back TOC Conditionals — “Decisions, Decisions, ...”

9.2.2 Truth Values in C++

At the heart of binary logic is the manipulation ovalues:

- T or true

- F or false

.

In C++ the actual representations for truth value

- the integer/float/double

zero

for

false

,

and

- any

nonzero

value for

true

.

1. George Boole, a nineteenth-centruy logician and mathematician

Page 9: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 9 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

r than ‘\0’

First Back TOC Conditionals — “Decisions, Decisions, ...”

Examples:

• All of the following is interpreted as false:

- int k = 0;

- float m = 0; double n = 0;

- char c = ‘\0’

• All of the following is interpreted as true:

- int k = 1, m = -7, n = 11;

- float p = 1.414;

- float q = 0.0001;

- char ch1 = ‘g’, ch2 = ‘4’; // any other characte

Page 10: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 10

Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ersion 2)

the second

“;

by zero.\n”;

First Back TOC Conditionals — “Decisions, Decisions, ...”

Example: Division with Check for Zero Divider (v

// Divide the first number by

#include <iostream.h>

void main(){

int a, b;

cout << “Enter two numbers: cin >> a >> b;

if (b) cout << a/b << ‘\n’;else cout << “Cannot divide

}

Page 11: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 11 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

1

mber X = ";

." << endl;

" << endl;

First Back TOC Conditionals — “Decisions, Decisions, ...”

Example: Checking for numbers between 0 and

#include <iostream.h>#include <math.h>

void main(){

float X;

cout << "Enter a positive nucin >> X;

if (floor(X))

cout << "X is 1 “;cout << “or greater than 1

elsecout << "X is less than 1.

}

Page 12: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 12

Chapter 9: Structured Programming with Control Structures

©

Christian Jacob

Prev Next Last

ion

”;

First Back TOC Conditionals — “Decisions, Decisions, ...”

Attention: The if condition accepts any express

int k = 1;

if (

k = 0

)cout << “It´s a zero.\n”;

elsecout << “It´s “ << k << “.\n

What does this program section return?

Page 13: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 13 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

nd c2

nd c3d not c3

1

First Back TOC Conditionals — “Decisions, Decisions, ...”

9.2.3 Nested if Statements

if (c1) {if (c2)

statement_1

; // c1 a

if (c3)

statement_2

; // c1 aelse

statement_3

; // c1 an}else

statement_4

; // not c

Page 14: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 14 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

er

gative

10< 10”;

nd 15 “ < 15”; // > 15

;

First Back TOC Conditionals — “Decisions, Decisions, ...”

Example: Identifying the value range of a numb

if (x >= 0) // x is non-ne{

if (x < 10)

// ... and x <

cout << “0 <= “ << x << “ else

// x >= 10

{ if (x < 15)

// between 10 a

cout << “10<= “ << x << else cout << x <<“ >= 15”;

}}else

// x < 0

{ cout << x << “ is negative.”}

Page 15: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 15 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

15

x >= 15

false

First Back TOC Conditionals — “Decisions, Decisions, ...”

Behaviour diagram of example program

0 <= x < 10x < 0

x >= 0false

x < 10

x <

10 <= x < 15

true

true false

true

Page 16: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 16

Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

lue that will ession, evaluation

ent

1/n )

First Back TOC Conditionals — “Decisions, Decisions, ...”

9.2.4 Short-Circuit Evaluation

As soon as a compound expression produces a vacompletely determine the value of the total exprstops.

Example:

if (n != 0)if (0 < x && x < 1/n) statem

More efficient:

if ( (n != 0) && 0 < x && x <

statement

Page 17: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 17 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

;

atted!

First Back TOC Conditionals — “Decisions, Decisions, ...”

9.2.5 The if-else-if Ladder

if(

condition

)

statement

;else

if(

condition

)

statement

;else

if(

condition

)

statement

;…

else

statement

This deeply nested

if-else

structure can be re-form

Page 18: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 18 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

statements):

First Back TOC Conditionals — “Decisions, Decisions, ...”

Reformatted nested if-else structure (with single

if(condition

)

statement

;else if(

condition

)

statement

;else if(

condition

)

statement

;…else

statement

;

Page 19: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 19 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

First Back TOC Conditionals — “Decisions, Decisions, ...”

Example:

if (x < 0)… // x is negative

else if (x > 0)… // x is positive

else … // x is zero

Page 20: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 20

Chapter 9: Structured Programming with Control Structures

©

Christian Jacob

Prev Next Last

ent sequences):

First Back TOC Conditionals — “Decisions, Decisions, ...”

Reformatted nested if-else structure (with statem

if (condition

){

statement_sequence

}else {if (

condition

){

statement_sequence

}else {if (

condition

){

statement_sequence

}…else {

statement_sequence

}

Page 21: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 21 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

)

}

First Back TOC Conditionals — “Decisions, Decisions, ...”

9.2.6 The switch Statement

switchstatement switch

(

selectionexpression

{

case

constant

:

statement

default

:

statement

Page 22: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 22 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

First Back TOC Conditionals — “Decisions, Decisions, ...”

A typical switch structure:

switch(

selection_expression

){case

constant1

:

statement_sequence

break;case

constant2

:

statement_sequence

break;case

constant3

:

statement_sequence

break;…

default

:

statement_sequence

}

Page 23: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 23 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ade

de;

First Back TOC Conditionals — “Decisions, Decisions, ...”

Example: Convert final grade (0-100) to letter gr

int finalGrade; char letterGra

switch (finalGrade/10) {

case 9: letterGrade = ‘A’; break;

case 8: letterGrade = ‘B’; break;

case 7: letterGrade = ‘C’; break;

case 6: letterGrade = ‘D’; break;

default: letterGrade = ‘F’;}

Page 24: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 24

Chapter 9: Structured Programming with Control Structures

©

Christian Jacob

Prev Next Last

ade

de;

;break;break;break;break;

First Back TOC Conditionals — “Decisions, Decisions, ...”

Example: Convert final grade (0-100) to letter gr

int finalGrade; char letterGra

switch (finalGrade/10) {

case 10: cout << “Wow--100!”case 9: letterGrade = ‘A’; case 8: letterGrade = ‘B’; case 7: letterGrade = ‘C’; case 6: letterGrade = ‘D’; default: letterGrade = ‘F’;

}

Page 25: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 25

Chapter 9: Structured Programming with Control Structures

©

Christian Jacob

Prev Next Last

tch: A”;

First Back TOC Conditionals — “Decisions, Decisions, ...”

9.2.7 Nested switch Statements

switch(ch1) {

case

‘A’: cout << “Outer switch: A”;switch(ch2) {

case

‘A’: cout << “Inner swibreak;

case

‘B’:// …

}break;

case

‘B’:// …

default:// …

}

Page 26: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 26 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

nd Over

f statements

First Back TOC Loops — “Doing Things Over and Over Again ...”

9.3 Loops — “Doing Things Over aAgain ...”

Loops are control structures that repeat a series owithout re-typing them.

Loops are commonly used for …

• counting

• summing

• repeated multiplication, increment, decrement

• keeping track of values (current, previous)

• repeating a sequence of commands or actions

• ...

Page 27: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 27

Chapter 9: Structured Programming with Control Structures

©

Christian Jacob

Prev Next Last

tering a loop

peated

ted in order to repetition started

the control flow

First Back TOC Loops — “Doing Things Over and Over Again ...”

Definitions around loops:

• Loop entry: statement(s) before en

• Loop body: statement(s) that are re

• Loop condition: expression to be evaluadecide whether a new (= iteration) should be

Loop exit

: end of the loop, whereleaves the loop

Page 28: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 28 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

uld always be clear

enter the loop.

nt to continue the

exit the loop.

First Back TOC Loops — “Doing Things Over and Over Again ...”

9.3.1 An Abstract View of Loops

When you write a repetition instruction, you shoabout these three issues:

1. Enter: The conditions under which you want to

2. Continue: The conditions under which you waloop.

3.

Exit

: The conditions under which you want to

Page 29: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 29 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

First Back TOC Loops — “Doing Things Over and Over Again ...”

General Loop Structure

Test1(pretest)

Yes? No?

Test2(post-test)

Loopbody

No?Yes?

Page 30: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 30 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ith the loop need to consider

op body to execute.

at is always true, a executes at least

its statements, the ntinue.

ry condition):

First Back TOC Loops — “Doing Things Over and Over Again ...”

The Three Loop Conditions

To understand how to construct a correct loop, wcondition correctly related to the loop body, we three conditions:

• Entry condition:

the condition that must hold in order for the lo

Alternatively, an entry condition may be one thtrivial condition, so that the loop body always once.

After entering a loop and after having executedquestion arises whether to continue or not to co

• Repeat or continuation

condition (often: = ent

Stay in the loop if this condition is true.

Exit

or

termination

condition:

Exit the loop if this condition is true.

Page 31: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 31 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ples:

n=0; n<10; n++)... }

;

( n < 10 )... n++; ... }

First Back TOC Loops — “Doing Things Over and Over Again ...”

9.3.2 Three General Loop Patterns

Pretest loop with continuation condition

PretestEntry/repeat?

Yes No

Loopbody

Exam

for ({

n = 0

while{

Page 32: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 32 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

mple:

0;

{... n++; ...hile ( n < 10 );

First Back TOC Loops — “Doing Things Over and Over Again ...”

Post-test loop with continuation condition

Repeat?

Loopbody

NoYes

Exa

n =

do

} w

Page 33: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 33 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

:

(true)

n++; ...

n>=10) break;

First Back TOC Loops — “Doing Things Over and Over Again ...”

Post-test loop with exit condition

Exit?

Loopbody

YesNo

Example

n = 0;

while {

...

if (}

Page 34: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 34 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ement)

ement)

PretestEntry/repeat?

Yes No

Loopbody

First Back TOC Loops — “Doing Things Over and Over Again ...”

9.3.3 The for Loop — Fixed Repetition

• Repeating a single statement

for(

entry

;

exit_test

;

in_de_cr

statement

;

• Repeating sequences of statements

for(

entry

;

exit_test

;

in_de_cr

{

statement

_

sequence

}

Generally,

for

loops are count-controlled.

Page 35: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 35 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

3 = 3 + 2 = 5

4 = 5 + 3 = 8

5 = 8 + 5 = 13

First Back TOC Loops — “Doing Things Over and Over Again ...”

Example: Calculating Fibonacci numbers:

f0 = 0

f1 = 1

f

n

= f

n-1

+ f

n-2

A few Fibonacci numbers, calculated iteratively:

f

2

= f

1

+ f

0

= 1 + 0 = 1 f

5

= f

4

+ f

f

3

= f

2

+ f

1

= 1 + 1 = 2 f

6

= f

5

+ f

f

4

= f

3

+ f

2

= 2 + 1 = 3 f

7

= f

6

+ f

Page 36: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 36 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

cci number

n-th

evious_fib;

-2

-1

First Back TOC Loops — “Doing Things Over and Over Again ...”

/* Calculating the n-th Fibona

Basic idea to calculate the Fibonacci number:

next_fib = current_fib + pr*/

int prev_fib = 0; // = fnint current_fib = 1; // = f

n

int next_fib; // = f

n

int n, i;

Page 37: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 37 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

<< endl;ld you “;ndl;

>= 0: “;

rev_fib;

= “;

First Back TOC Loops — “Doing Things Over and Over Again ...”

main(){ cout << “Fibonacci numbers” cout << “Which F. number wou cout << “to calculate?” << e

cout << “Enter an integer n cin >> n;

for(i = 0; i < n; i++){next_fib = current_fib + pprev_fib = current_fib;current_fib = next_fib;

}cout << n << “-th Fibonacci

cout << prev_fib;}

Pretest

Entry/repeat?Yes No

Loopbody

Page 38: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 38 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

s

)’;

First Back TOC Loops — “Doing Things Over and Over Again ...”

9.3.4 Variations on the for Loop

• Several initialization and increment expression

for(

x=0, y=10

; x<=10;

++x, --y

cout << x << ‘ ‘ << y << ‘\n

Page 39: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 39 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

the

kbhit()

is pressed << i << ‘ ‘;

First Back TOC Loops — “Doing Things Over and Over Again ...”

• Exiting a for loop when a key is pressed (using

function)

int main(){

int i;

// print numbers until a keyfor(i=0; !kbhit(); i++) cout

return(0);}

kbhit()

returns

true

(!= 0)

- if a key has been pressed

- otherwise

false

(== 0).

Pretest

Entry/repeat?Yes No

Loopbody

Page 40: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 40 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

PretestEntry/repeat?

Yes No

Loopbody

First Back TOC Loops — “Doing Things Over and Over Again ...”

9.3.5 The while Loop — Pretest

• Single statement to repeat

while(

expression

)

statement

;

• Sequence of statements to repeat

while(

expression

){

statement_sequence

}

Generally,

while

loops are event-controlled.

Page 41: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 41 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

-2

-1

First Back TOC Loops — “Doing Things Over and Over Again ...”

Example: The n-th Fibonacci number :

f0 = 0

f

1

= 1

f

n

= f

n-1

+ f

n-2

Implemented with a

WHILE

loop:

int previous_fib = 0; // = f

n

int current_fib = 1; // = f

n

int next_fib; // = f

n

int n,

i = 0

;

Page 42: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 42 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

revious_fib;;

“;

First Back TOC Loops — “Doing Things Over and Over Again ...”

main(){

cout << “Enter n >= 0: “; cin >> n;

while(

i < n

) {next_fib = current_fib + pprevious_fib = current_fibcurrent_fib = next_fib;

i++

;}

cout << previous_fib << “ iscout << n << “-th fib;

return(0);}

Pretest

Entry/repeat?Yes No

Loopbody

Page 43: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 43 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ent code

revious_fib;;

“;

First Back TOC Loops — “Doing Things Over and Over Again ...”

main() // a little more effici{

cout << “Enter n >= 0: “; cin >> n;

while(

i++ < n

) {next_fib = current_fib + pprevious_fib = current_fibcurrent_fib = next_fib;

}

cout << previous_fib << “ iscout << n << “-th fib;

return(0);}

Pretest

Entry/repeat?Yes No

Loopbody

Page 44: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 44 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

re

n >> n;

>= “ << n;

First Back TOC Loops — “Doing Things Over and Over Again ...”

Taking care of special cases (1):

// variable declarations go he

main(){

cout << “Enter n >= 0: “; ci

if(n==0 || n==1)

{ cout << n;cout << “is the first fib return(0);

}

while(...) {...}...

return(0);}

Page 45: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 45 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

re

n >> n;

s: n = 0 or 1

>= “ << n;

First Back TOC Loops — “Doing Things Over and Over Again ...”

Taking care of special cases (1):

// variable declarations go he

main(){

cout << “Enter n >= 0: “; ci

if(n <= 1) {

// Special case

cout << n;cout << “is the first fib

}

else

{while(...) {...}

... } return(0);

}

Page 46: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 46 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

op

);

ation!

Repeat?

Loopbody

No

First Back TOC Loops — “Doing Things Over and Over Again ...”

9.3.6 The do-while Loop — A Post-Test Lo

• Single statement to repeat

do

statement

; while(

expression

• Sequence of statements to repeat

do{

statements

} while(

expression

);

Note

: A

do-while

loop always completes one iter

Yes

Page 47: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 47 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

HILE loop)

re

>> n;

revious_fib;;

“;r”;}

First Back TOC Loops — “Doing Things Over and Over Again ...”

Example: The n-th Fibonacci number (with DO-W

// Other initializations go he

int n,

i=0

;

void main(){

cout << “Enter

n > 0

: “; cin

do

{next_fib = current_fib + pprevious_fib = current_fibcurrent_fib = next_fib;

}

while

(

++i

< n);

cout << previous_fib << “ is cout << n << “-th fib. numbe

Repeat?

Loopbody

NoYes

Page 48: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 48 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

>> n;

revious_fib;;

s_fib;

r”;

First Back TOC Loops — “Doing Things Over and Over Again ...”

void main(){

cout << “Enter n > 0: “; cin

do

{next_fib = current_fib + pprevious_fib = current_fibcurrent_fib = next_fib;

}

while

(++i < n);

cout <<

(n==0) ? 0 : previou

cout << “ is “; cout << n << “-th fib. numbe}

Repeat?

Loopbody

NoYes

Page 49: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 49 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

First Back TOC Loops — “Doing Things Over and Over Again ...”

9.3.7 Infinite Loops

• Using for

for(;;) { … }

• Using

while

while(1) { … }

Page 50: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 50 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

am? (y/n)\n”;

m continued

end.\n”;

’ or \’n\’.”;

am

First Back TOC Loops — “Doing Things Over and Over Again ...”

Checking for keyboard input:

while (true) { cout << “Continue with progr cin >> answer;

switch(answer) { case ‘y’: case ‘Y’: break; // progra case ‘n’: case ‘N’: cout << “Program

return(0); default:

cout << “Enter only \’y\ }}// further statements of progr

Exit?

Loopbody

YesNo

Page 51: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 51 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

long time

First Back TOC

Break

and

Continue

9.4 Break and Continue

9.4.1 Using

break

to Exit Loops

for(i=0; i<1000; i++) // for a{

// do somethingif(kbhit()) break;

}

Page 52: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 52 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

e loop

e loop

Exit?

Loopbody

Yes

Exit?

Loopbody

Yes

First Back TOC

Break

and

Continue

Alternative with infinite for loop:

for(;;){ // infinit// do somethingif(kbhit()) break;

}

Alternative with infinite

while

loop:

while(1){ // infinit// do somethingif(kbhit()) break;

}

No

No

Page 53: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 53 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

First Back TOC

Break

and

Continue

Using break to exit loops

int main(){

int t, count;

for(t = 0; t < 100; t++) {count = 1;

for(;;) {cout << count << ‘ ‘;count++;if(count == 10) break;

}cout << ‘\n’;

return(0);}

Page 54: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 54 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

ol structure

First Back TOC

Break

and

Continue

9.4.2 Using continue

Continue is used to bypass a loop´s normal contr

int main(){

int x;

for(x=0; x<=100; x++){

if(x % 2) continue;cout << x << ‘ ‘;

}

return(0);}

Page 55: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 55 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

amming”

s a valid C++

as follows:

on is:

t_sequence }

First Back TOC Using

goto

— “Spaghetti Programming”

9.5 Using goto — “Spaghetti Progr

The

goto

requires a label for operation. A

label

iidentifier followed by a colon.

A loop from 1 to 100 could be written using

goto

x = 1;

start

:x++;

statement_sequence

if(x<100) goto

start

;

However, a much more comprehensive formulati

for(x=1; x<100; x++){

statemen

Page 56: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 56 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

e loop?

First Back TOC Guidelines for Loops

9.6 Guidelines for Loops

9.6.1 How to Design Loops

Process:

• What is the process being repeated?

• How should the process be

initialized

?

• How should the process be

updated

?

Condition:

• How should the condition be

initialized

?

• How should the condition be

updated

?

• What is the condition that

ends

the loop?

After the Loop:

• What is the

state of the program

on exiting th

Page 57: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 57 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

tatement

lled loop

, the

for

ount++)

First Back TOC Guidelines for Loops

9.6.2 Guidelines for Choosing a Looping S

• If the repeated process is a simple count-controloop is a “natural” choice:

for (count = 1; count <= 10; c//

statement

;

… is equivalent to …

count = 1;while (count <= 10){

//

statement

;count++;

}

Page 58: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 58 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

tialize, test, and

e reduces the

op

, whose body

hile

loop is

op, but nothing is op.

es clarifies the

d loop design.

, do-while, and for.

First Back TOC Guidelines for Loops

Concentrating the three loop control actions (iniincrement/decrement) in the for loop in one placchances of errors.

• If the iterated process is an event-controlled loalways has to be executed at least once, a do-wappropriate.

• If the iterated process is an

event-controlled lo

known about the first execution, use a

while

lo

• An infinite loop with

break

statements sometimcode.

More often, however, it reflects an undiscipline

Use it only after careful consideration of

while

Page 59: Chapter 9 Structured Programming Using Control Flow …pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/09-Cont… · Chapter Overview 9.3 Loops — “Doing Things Over

Page 59 Chapter 9: Structured Programming with Control Structures © Christian Jacob

Prev Next Last

, Boston, MA: WCB/

First Back TOC References

9.7 References

• G. Blank and R. Barnes, The Universal MachineMcGraw-Hill, 1998. Chapter 7.