c++ programming lecture 6 control structure ii (repetition) the hashemite university computer...

31
C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

Upload: phillip-atkins

Post on 18-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

C++ ProgrammingLecture 6

Control Structure II (Repetition)

The Hashemite UniversityComputer Engineering

Department

(Adapted from the textbook slides)

Page 2: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 2

Outline Introduction. while Repetition Structure. for Repetition Structure. do/while Repetition Structure. continue and break Statements. Formulating Algorithms. Nested Control Structures. Examples.

Page 3: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 3

Introduction In the last lecture we have explored the

selection control structures. In this lecture we will explore another

type of control structure in which part of the code is repeated number of times.

Repetition (or looping) control structures: while. for. do/while.

Page 4: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 4

Types of Looping Two types of repetition or looping exist:

Sentinel-Controlled Repetition. In this type you do not know the number of times

the body of the loop must be repeated, i.e. do not know the number of loop iterations.

Mainly you use while, and do/while control structures for this type of looping.

Counter-Controlled Repetition. In this type you know the number of times the

body of the loop must be repeated, i.e. the number of loop iterations is defined in advance.

Mainly you use for control structures for this type of looping.

Page 5: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 5

while Repetition Structure I

Repetition structure Programmer specifies an action to be repeated while some

condition remains true. Also called looping or simply loop. Psuedocode

while there are more items on my shopping list Purchase next item and cross it off my list

while loop repeated until condition becomes false where the next line of code after while loop will be executed.

Another exampleint product = 2;while ( product <= 1000 ) product = 2 * product;

The body of the while loop is the code block contained within the braces after the while, otherwise it is the first statement after the while only.

Page 6: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 6

while Repetition Structure II Flowchart of while loop. Infinite loop:

Logical error in the while structure.

The condition of the while is always true, i.e. the body of the while loop does not modify the condition value.

Leaving the parenthesis after the while empty (i.e. you do not specify any condition) is syntax error.

product <= 1000 product = 2 * producttrue

false

Page 7: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 7

Essentials of Counter-Controlled Repetition Counter-controlled repetition requires:

The name of a control variable (or loop counter). The initial value of the control variable. The condition that tests for the final value of the control

variable (i.e., whether looping should continue). The increment (or decrement) by which the control

variable is modified each time through the loop. Example:

int counter =1; //initializationwhile (counter <= 10){ //repetition condition cout << counter << endl; ++counter; //increment

} As possible avoid the usage of floating point

counter values since floating points are approximate.

Page 8: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 8

for Repetition Structure I Handles all the details of counter-controlled

repetition in a concise way. The general format when using for loops is:

for (initialization; LoopContinuationTest; increment/decrement )

statement Example:

for( int counter = 1; counter <= 10; counter++ )

cout << counter << endl;

Prints the integers from one to ten Pay attention to the off-by-one error.

Page 9: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 9

for Repetition Structure II After the condition of the for is violated, the first

statement after the for loop is executed. The for loop body is the code block after it (if braces

exist) otherwise it is the first statement after for structure.

for loops can usually be rewritten as while loops:initialization;while ( loopContinuationTest){ statement increment;}

Initialization and increment as comma-separated listsfor (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl; //how many time this statement will execute

Page 10: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 10

for Repetition Structure III Scope of the counter variable defined inside for

loop differs based on the used C++ compiler: Known only inside for structure. Or known inside the whole program after the for

loop this is what is applicable for our case. The three parts of the for loop are optional, if the

condition is omitted this will create an infinite loop since the compiler assumes that the for condition is true.

What will happen if you omit one of the parts of the for loop and you have not modified it inside its body?? (Hint: check for infinite loops).

for loop parts can contain arithmetic expressions.

Flowchart of the for loop is similar to the while loop.

Page 11: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 11

do...while Repetition Structure I The do/while repetition structure is similar to the while

structure except that Condition for repetition tested after the body of the loop is

executed Format:

do { statement} while ( condition );

Example (letting counter = 1): do {cout << counter << " ";

} while (++counter <= 10); This prints the integers from 1 to 10

Pay attention to post/pre increment/decrement. Does it has any effect?

All actions are performed at least once.

Page 12: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 12

do...while Repetition Structure II

Flowchart of do...while loop

true

false

action(s)

condition

Page 13: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 13

break Statement break

Causes immediate exit from a while, for, do/while or switch structure

Program execution continues with the first statement after the structure

Common uses of the break statement: Escape early from a loop Skip the remainder of a switch structure

Using break outside a loop or switch (e.g. inside if/else) statement is a syntax error.

Page 14: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 14

continue Statement continue

Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop. Also, can be used with switch.

In while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executed

In the for structure, the increment/decrement expression is executed, then the loop-continuation test is evaluated

Using continue outside a loop or switch (e.g. inside if/else) statement is a syntax error.

Page 15: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 15

Formulating Algorithms (Counter-Controlled Repetition)

Counter-controlled repetition Loop repeated until counter reaches a

certain value. Definite repetition

Number of repetitions is known Example

A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

Page 16: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 16

Formulating Algorithms (Counter-Controlled Repetition)

Pseudocode for example:Set total to zeroSet grade counter to oneWhile grade counter is less than or equal to ten

Input the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by tenPrint the class average

Following is the C++ code for this example

Page 17: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 17

1 // Fig. 2.7: fig02_07.cpp

2 // Class average program with counter-controlled repetition3 #include <iostream>45 using std::cout;6 using std::cin;7 using std::endl;89 int main()10 {11 int total, // sum of grades 12 gradeCounter, // number of grades entered13 grade, // one grade14 average; // average of grades1516 // initialization phase17 total = 0; // clear total18 gradeCounter = 1; // prepare to loop1920 // processing phase21 while ( gradeCounter <= 10 ) { // loop 10 times22 cout << "Enter grade: "; // prompt for input23 cin >> grade; // input grade24 total = total + grade; // add grade to total25 gradeCounter = gradeCounter + 1; // increment counter26 }2728 // termination phase29 average = total / 10; // integer division30 cout << "Class average is " << average << endl;3132 return 0; // indicate program ended successfully33 }

The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.

Page 18: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 18

Enter grade: 98Enter grade: 76Enter grade: 71Enter grade: 87Enter grade: 83Enter grade: 90Enter grade: 57Enter grade: 79Enter grade: 82Enter grade: 94Class average is 81

Page 19: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 19

Formulating Algorithms (Sentinel-Controlled Repetition) I

Suppose the problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run.

Unknown number of students - how will the program know to end?

Sentinel value Indicates “end of data entry” Loop ends when sentinel inputted Sentinel value chosen so it cannot be

confused with a regular input (such as -1 in this case)

Page 20: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 20

Formulating Algorithms (Sentinel-Controlled Repetition) II

Top-down, stepwise refinement begin with a pseudocode

representation of the top:Determine the class average for the quiz

Divide top into smaller tasks and list them in order:

Initialize variablesInput, sum and count the quiz gradesCalculate and print the class average

Page 21: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 21

Formulating Algorithms (Sentinel-Controlled Repetition) III

Many programs can be divided into three phases:

Initialization Initializes the program variables

Processing Inputs data values and adjusts program variables

accordingly Termination

Calculates and prints the final results. Helps the breakup of programs for top-down refinement.

Refine the initialization phase fromInitialize variables

toInitialize total to zeroInitialize counter to zero

Page 22: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 22

Formulating Algorithms (Sentinel-Controlled Repetition) IV

RefineInput, sum and count the quiz grades

to Input the first grade (possibly the sentinel)While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel)

RefineCalculate and print the class average

toIf the counter is not equal to zero Set the average to the total divided by the counter Print the averageElse Print “No grades were entered”

Page 23: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 23

1 // Fig. 2.9: fig02_09.cpp

2 // Class average program with sentinel-controlled repetition.

3 #include <iostream>

4

5 using std::cout;

6 using std::cin;

7 using std::endl;

8 using std::ios;

9

10 #include <iomanip>

11

12 using std::setprecision;

13 using std::setiosflags;

14

15 int main()

16 {

17 int total, // sum of grades

18 gradeCounter, // number of grades entered

19 grade; // one grade

20 double average; // number with decimal point for average

21

22 // initialization phase

23 total = 0;

24 gradeCounter = 0;

25

26 // processing phase

27 cout << "Enter grade, -1 to end: ";

28 cin >> grade;

29

30 while ( grade != -1 ) {

Data type double used to represent decimal numbers.

Page 24: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 24

31 total = total + grade; 32 gradeCounter = gradeCounter + 1; 33 cout << "Enter grade, -1 to end: "; 34 cin >> grade; 35 }3637 // termination phase38 if ( gradeCounter != 0 ) { 39 average = static_cast< double >( total ) / gradeCounter;40 cout << "Class average is " << setprecision( 2 )41 << setiosflags( ios::fixed | ios::showpoint )42 << average << endl;43 }44 else45 cout << "No grades were entered" << endl;4647 return 0; // indicate program ended successfully48 }

Enter grade, -1 to end: 75Enter grade, -1 to end: 94Enter grade, -1 to end: 97Enter grade, -1 to end: 88Enter grade, -1 to end: 70Enter grade, -1 to end: 64Enter grade, -1 to end: 83Enter grade, -1 to end: 89Enter grade, -1 to end: -1Class average is 82.50

setiosflags(ios::fixed | ios::showpoint) - stream manipulator

ios::fixed - output numbers with a fixed number of decimal points.

ios::showpoint - forces decimal point and trailing zeros, even if unnecessary: 66 printed as 66.00

| - separates multiple option.

setprecision(2) - prints only two digits past decimal point.

Programs that use this must include <iomanip>

static_cast<double>() - treats total as a double temporarily.

Required because dividing two integers truncates the remainder.

gradeCounter is an int, but it gets promoted to double.

Page 25: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 25

Nested control structures I Problem:

A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition".

We can see that The program must process 10 test results. A counter-

controlled loop will be used. Two counters can be used—one to count the number

of students who passed the exam and one to count the number of students who failed the exam.

Each test result is a number—either a 1 or a 2. If the number is not a 1, we assume that it is a 2.

Top level outline:Analyze exam results and decide if tuition should be raised

Page 26: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 26

Nested control structures II First Refinement:

Initialize variablesInput the ten quiz grades and count passes and failuresPrint a summary of the exam results and decide if tuition should be raised

RefineInitialize variables

to Initialize passes to zeroInitialize failures to zeroInitialize student counter to one

Page 27: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 27

Nested control structures III

RefineInput the ten quiz grades and count passes and failures

to While student counter is less than or equal to ten

Input the next exam resultIf the student passed Add one to passesElse Add one to failuresAdd one to student counter

RefinePrint a summary of the exam results and decide if tuition should be

raised to

Print the number of passesPrint the number of failuresIf more than eight students passed

Print “Raise tuition”

Page 28: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 28

1 // Fig. 2.11: fig02_11.cpp

2 // Analysis of examination results

3 #include <iostream>

4

5 using std::cout;

6 using std::cin;

7 using std::endl;

8

9 int main()

10 {

11 // initialize variables in declarations

12 int passes = 0, // number of passes

13 failures = 0, // number of failures

14 studentCounter = 1, // student counter

15 result; // one exam result

16

17 // process 10 students; counter-controlled loop

18 while ( studentCounter <= 10 ) {

19 cout << "Enter result (1=pass,2=fail): ";

20 cin >> result;

21

22 if ( result == 1 ) // if/else nested in while

23 passes = passes + 1;

Page 29: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 29

3. Print results

Program Output

24 else

25 failures = failures + 1;

26

27 studentCounter = studentCounter + 1;

28 }

29

30 // termination phase

31 cout << "Passed " << passes << endl;

32 cout << "Failed " << failures << endl;

33

34 if ( passes > 8 )

35 cout << "Raise tuition " << endl;

36

37 return 0; // successful termination

38 }

Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 2Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Passed 9Failed 1Raise tuition

Page 30: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 30

Examples Using while & for Loop

On board. Grading system while counting the

number of grades. Drawing shapes using for loop.

Page 31: C++ Programming Lecture 6 Control Structure II (Repetition) The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 31

Additional Notes

This lecture covers the following material from the textbook: Fourth Edition:

Chapter 2: Sections 2.7 - 2.18