• No results found

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

N/A
N/A
Protected

Academic year: 2021

Share "What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be..."

Copied!
13
0
0

Loading.... (view fulltext now)

Full text

(1)

1

CSC 211 Intermediate Programming

CSC 211 Intermediate Programming

Looping

Looping

2

What is a Loop?

„

A loop is a repetition control structure

„

It causes a single statement or a group of

statements to be executed repeatedly

„

It uses a condition to control iteration

„

Loop continues as long as condition is TRUE

3

Types of Loop Testing

Begin loop

End loop Statements

in loop

Endless loop

false Test Condition

End loop Statements

in loop true

Pretest loop

Begin loop

Test Condition Statements

in loop

false

true

Posttest loop

4

Pretest Loops in C++

„

One pretest loop in C++ is the while loop

„

A condition is used to control the loop

„

The condition is put between parentheses

while (condition)

statement;

while (condition)

{

statement1

;

statement2

;

. . .

}

5

Loops can be ...

„

Count controlled

„

repeat a specified number of times

„

Event-controlled

„

some condition within the loop body changes

and this causes the repeating to stop

6

Count-controlled loops

„

They contain:

„

An initialization of the loop control variable

„

A condition to test for continuing the loop

„

An update of the loop control variable to be

executed with each iteration of the body

(2)

7

int count;

count = 4; // initialize loop variable while (count > 0) // test condition

{

cout << count << endl; // repeated action count--; // update loop variable }

cout << "Done" << endl;

Count-controlled Loop

8

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

Count-controlled Loop

9

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

4

Count-controlled Loop

10

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

4

Count-controlled Loop

True

11

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

4

Count-controlled Loop

4

12

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

3

Count-controlled Loop

4

(3)

13

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

3

Count-controlled Loop

4 True

14

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

3

Count-controlled Loop

4 3

15

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

2

Count-controlled Loop

4 3

16

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

2

Count-controlled Loop

4 3 True

17

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

2

Count-controlled Loop

4 3 2

18

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

1

Count-controlled Loop

4 3 2

(4)

19

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

1

Count-controlled Loop

4 3 2 True

20

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

1

Count-controlled Loop

4 3 2 1

21

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

Count-controlled Loop

4 3 2 1

0

22

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

0

Count-controlled Loop

4 3 2 1 False

23

int count;

count = 4;

while (count > 0) {

cout << count << endl;

count--;

}

cout << "Done" << endl;

Output

count

0

Count-controlled Loop

4 3 2 1 Done

24

Event-controlled Loops

„

Sentinel controlled

„

keep processing data until a special value which is

not a possible data value is entered to indicate

that processing should stop

„

End-of-file controlled

„

keep processing data as long as there is more

data in the file

„

Flag controlled

„

keep processing data until the value of a flag

changes in the loop body

(5)

25

Examples of Kinds of Loops

Read blood pressures until a

dangerously high BP (200 or

more) is read.

Flag controlled loop

Read all the blood pressures from

a file no matter how many are

there.

End-of-file controlled loop

Read blood pressures until a

special value (like -1) selected by

you is read.

Sentinel controlled loop

Read exactly 100 blood pressures

from the user.

Count controlled loop

26

A Sentinel-controlled Loop

„

Sentinel value – A special value of input

that causes the program to stop a loop

„

Must be a value that would not occur in

the normal course of operation

„

Requires a “priming read” if done with a

while loop

„

“priming read” means you read one set of

data before the while

27

Example

int bloodPressure, total = 0;

cout << "Enter a blood pressure (-1 to stop ): ";

cin >> bloodPressure;

while (bloodPressure != -1) // while not sentinel {

total = total + bloodPressure;

cout << "Enter a blood pressure (-1 to stop): ";

cin >> bloodPressure;

}

cout << total << endl;

28

End-of-File Controlled Loop

„

Depends on fact that a file goes into fail

state when you try to read a data value

beyond the end of the file

„

Several ways to accomplish

29

Using the ifstream variable

„ Uses a priming read

„ The variable alone is the loop control variable

„ If the stream has entered a fail state, it has a false, otherwise it has a true

ifstream inFile(“data.txt”);

int x;

inFile >> x;

while(inFile) { //Statements

inFile >> x;

}

30

Combining the steps

„

The priming read can be done as part of the

condition

„

The logic is still the same as the previous slide

ifstream inFile(“data.txt”);

int x;

while(inFile >> x)

{

//statements

}

(6)

31

eof Function

„

eof function returns a true if the program has read

past the end of the file; otherwise it returns a false

„

Requires priming read

ifstream inFile(“data.txt”);

int x;

inFile >> x;

while(!inFile.eof())

{ //Statements

inFile >> x;

}

32

Assignment

„

With a partner write two loops that

would read from the same file,

money.dat, and print the contents to

the screen.

„

The program should loop until the end

of the file is reached.

„

Each of the two loops should use a

different method

33

Flag-controlled Loops

„

Use a bool type flag variable and

initialize it (to true or false)

„

Use meaningful name for the flag

„

A condition in the loop body changes

the value of the flag

„

Test for the flag in the loop test

condition

34

Example

int bloodPressure, countGoodReadings = 0;

bool isSafe = true; // initialize Boolean flag

while (isSafe) {

cin >> bloodPressure;

if (bloodPressure >= 200)

isSafe = false; // change flag value else

countGoodReadings++;

}

cout << countGoodReadings << endl;

35

Posttest Loops in C++

„

Posttest done with the do while statement.

„

Also uses a condition placed in parentheses.

do

statement;

while (condition);

do

{

statement1

;

statement2

;

. . .

} while (condition);

36

Example

// display the numbers from 4 to 0 // using the posttest do while loop

int count;

count = 4; // initialize loop variable do

{

cout << count << endl; // repeated action count--; // update loop variable } while (count > 0); // test condition

cout << "Done" << endl;

(7)

37

Sentinel-controlled loops

with do while

„

Does not require a “priming read”

int bloodPressure = 0, total = 0;

do {

total = total + bloodPressure;

cout << "Enter a blood pressure (-1 to stop): ";

cin >> bloodPressure;

} while (bloodPressure != -1); // while not sentinel cout << total << endl;

38

while vs. do while

Loop body is always

executed at least once.

Loop body may not be

executed at all.

The loop condition is

tested after executing the

loop body.

The loop condition is

tested before executing

the loop body.

It is a Posttest loop.

It is a Pretest loop.

do while

while

39

Accumulating

„

Loops often used to

„

Count data values

„

Sum data values

„

Keep track of previous and current values

„

This requires accumulating and counting

40

Accumulating (Cont ..)

„

Accumulating is keeping a running result

„

Take the value of a variable, modify the value,

and store it back in the original variable

total = total + new;

„

Any arithmetic operator (+ − * / %) can be part

of an accumulation

total = total * new;

„

Counting is a simple form of accumulation

count = count + 1;

„

Make sure you INITIALIZE accumulation or

counting variables

41

Accumulating (Cont ..)

„

Accumulation operators

„

Shorthand for performing accumulation

„

Same precedence & associativity as assignment

Example Equivalent statement

total += new; total = total + new;

total -= new; total = total - new;

total *= new; total = total * new;

total /= new; total = total / new;

total %= new; total = total % new;

42

Example

// calculate the sum of the integers from 1 to 10 // Initialize the counting and accumulating variables int number = 1, sum = 0;

while ( number <= 10) {

sum += number; // accumulating the sum // sum = sum + number;

number += 1; // counting, number = number + 1;

}

cout << "The sum is " << sum << endl;

(8)

43

Assignment

„

Write a C++ program to calculate the

factorial of 10.

44

The for loop

„

A specially designed count-controlled loop

for (initialization; test; updatecounter)

statement;

for (initialization; test; updatecounter)

{

statement1

;

statement2

;

. . .

}

45

The for loop

„

Actions of the for spread out around

the loop

„

initialization occurs only ONCE at the start

„

testing is the first repeated action of the

loop (it gets done before the body each

iteration)

„

updatecounter occurs at the end of the loop

body

46

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Example

Initialization Test Updatecounter

End Body

47

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

48

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

1

(9)

49

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

1 True

50

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

1

1

51

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

2

1

52

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

2 True

1

53

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

2

1 2

54

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

3

1 2

(10)

55

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

3 True

1 2

56

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

3

1 2 3

57

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

4

1 2 3

58

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Output

count

Example (Cont ..)

4 False

1 2 3 When the loop control condition is evaluated and has value false, the loop is said to be “satisfied” and control passes to the statement following the for structure.

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

59

int count;

for (count = 1; count <= 3; count++) {

cout << count << endl;

}

cout << "Count = " << count << endl;

Example (Cont ..)

Output

count

4

1 2 3 Count = 4

60

Assignment

„

Write a program to ask the user to

enter 5 integers and then find the

maximum value.

(11)

61

„

What output do you expect from this loop?

int count;

for (count = 0; count < 10; count++)

cout << "*";

„

What about this one?

int count;

for (count = 0; count < 10; count++);

cout << "*";

Programming Error I

62

Programming Error I (Cont ..)

„

The second loop in the previous slide does

not produce any output. Why?

„

The ; right after the ( ) means that the body

statement is a null statement

„

In general, the Body of the for loop is whatever

statement immediately follows the ( )

„

That statement can be a single statement, a block,

or a null statement

„

Actually, the second code segment in the

previous slide outputs one * after the loop

completes its counting to 10

63

Programming Error II

„

C++ will accept any simple data type as a

counter, but floating-point counters can

lead to unexpected results

„

Floating-point values are stored in E-

notation and approximated to decimal

values

„

So the value 1.0 might be approximated to

1.000000000001 or 0.999999999999

64

Programming Error II (Cont ..)

float count;

cout << "Values from 0 to 1 in steps of 0.1\n" << endl;

cout << fixed << setprecision(2);

for (count = 0; count <= 1; count += 0.1) cout << count << " ";

cout << endl << "Final count: " << count << endl;

Possible Output

Values from 0 to 1 in steps of 0.1

0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 Final count: 1.00

65

Programming Error II (Cont ..)

int count;

cout << "Values from 0 to 1 in steps of 0.1\n" << endl;

cout << fixed << setprecision(2);

for (count = 0; count <= 10; count++) cout << count/10.0 << " ";

cout << endl << "Final count: " << count/10.0 << endl;

Output

Values from 0 to 1 in steps of 0.1

0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00 Final count: 1.10

66

Nested Loops

„

A loop within another is a nested loop

„

Nest as deep as you want, but …

„

An inner loop must be entirely contained within an

outer one

„

If the loops are counter controlled, each loop must

have a different loop counter variable

„

Nested loops used often for rows and

columns

„

Outer loop controls the rows

„

Inner loop controls the columns

(12)

67

Example of Nested Loops

Output:

int column, row;

for (row = 1; row <= 4; row++) {

for (column = 1; column <= 5; column++) cout << setw(2) << row * column << " ";

cout << endl;

}

1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20

68

Assignment

Write a program to display the following output:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

69

Validation Loops

„

Sometimes you may need to check for

validity of input data

„

The user can enter negative value where it

is supposed to be positive ( year )

„

The user can enter a value that is outside

the range of possible values (entering 110

for a test score)

„

This can be done with validation loops

„

Continue prompting the user for valid value

as long as invalid value is entered

70

Example

int score;

cout << "Enter the test score: ";

cin >> score;

// test score should be between 0 and 100 while ( score > 100 || score < 0) {

cout << "Invalid input, enter again: ";

cin >> score;

}

cout << endl << "The test score is " << score << endl;

71

Example (Cont ..)

Output

Enter the test score: -18 Invalid input, enter again: 110 Invalid input, enter again: 89

The test score is 89

72

The break statement

„

The break statement can be used with

switch or any of the 3 looping structures.

„

It causes an immediate exit from the switch,

while, do while, or for structure in which

it appears.

„

If the break is inside nested structures,

control exits only the innermost structure

containing it.

(13)

73

The continue statement

„

The continue statement is valid only within

loops.

„

It terminates the current loop iteration, but not

the entire loop.

„

In a for or while loop, continue causes

the rest of the body statement to be skipped -

in a for statement, the update is done.

„

In a do while loop, the exit condition is

tested, and if true, the next loop iteration

starts.

74

Loop Testing and Debugging

„

Beware of infinite loops - program doesn’t

stop

„

Check loop termination condition, and watch

for “off-by-1” problem

„

Trace execution of loop by hand with code

walk-through

„

Use debug output statements

References

Related documents

In this example, you know exactly how many times the loop body needs to be executed because the control variable count is used to count the number of executions. This type of loop

• The block (body) of code is executed once for each value in the sequence. • The

SIMULINK MODEL OF CLOSED LOOP SPEED CONTROL OF SEDC MOTOR USING CONTROLLED RECTIFIER..

for Loop Flow Chart Evaluate Control-variable Expression i false true Adjustment expression Statement(s) (loop-body) Next Statement Continue condition?.. for

Gaining the full potential from motion sources in testing applications requires the use of an electronic motion controller implementing closed-loop control of the pressure or

In the process of sending email, you will learn about C goto statement, it does not terminates the loop execution but it skip the current iteration of the loop and passes

We shall write a while loop with condition that it is true until it reaches given number, and during each iteration, we shall add this number to the sum ... break

loop exit - the point at which the iteration ends and control passes to the next statement after the loop termination condition - the condition that causes the iteration to