Tải bản đầy đủ (.ppt) (27 trang)

C++ lecture 6

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (358.8 KB, 27 trang )

C++ Programming
Lecture 6

Control Structure II
The Hashemite University
(Repetition)
Computer Engineering
Department

(Adapted from the textbook slides)


Outline









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



2


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.
The Hashemite University

3


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.
The Hashemite University


4


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 example
int 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.
The Hashemite University

5


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.

true
product <= 1000

product = 2 * product

false

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

6


Essentials of CounterControlled 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). (check counter value with
the condition)
The increment (or decrement) by which the control variable is
modified each time through the loop.

Example:
//the while body will execute 10 times

//the for body will execute 4 times

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

for (int i=0;i<7;i+=2)
{
Cout<<“looping”
}

As possible avoid the usage of floating point counter values since

floating points are approximate.
The Hashemite University

7


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.

The Hashemite University

8


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 lists
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl; //how many time this
statement will execute

The Hashemite University

9


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.
The Hashemite University
10


While and for example
 for (int z=8;z>0;z-=3)

cout<<”welcome”; // this will execute 3 times only
 for (int counter=-21;counter<3;counter*=-2)
cout<<“hi”; //this will execute

ONE time

 for (int counter=-21;counter>3;counter*=-2)

int loop=5;
While (loop>=5 &&
loop<10)

cout<<“hi”; //this will never execute
{
Convert the following for loop into while loop cout<<“ok”;
for (int loop=5; loop>=5&&loop<10;loop++)
loop++;
cout<<“ok”;
}

 How many times this loop will repeat ??

for (int counter=30;counter>0;counter/=2)
cout<<“hi”<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.
The Hashemite University

12


do...while Repetition
Structure II


Flowchart of do...while loop

action(s)

true
condition
false


The Hashemite University

13


Examples (1)
for(float i=5.5;i<10;i++)
cout<
Note that even if variable i is float but it is used as integer counter in
the for loop, however it’s value is printed as float inside the body
for(int i=1;i<5;++i)
for(int i=1;i<5;i++)
cout<<"loop"<cout<<"loop"<The two for loops above will print loop 4 times. There is no difference
if the increment/decrement is pre or post inside the third part of
the for loop statement.

The Hashemite University

14


Examples (2)


Always be careful with the pre or post condition when applied
to the while or do/while repetition

int num=3;
while(++num<7)
cout<<"loop"<will be printed 3 times on the
screen

int num=3;
while(num++<7)
cout<<"loop"<will be printed 4 times on the
screen

int count=-3;
int count=-3;
do {
do {
cout<<"loop“<cout<<"loop“<}while(count++);// loop will be }while(++count);// loop will be
printed 4 times on the
printed 3 times on the
screen
screen
The Hashemite
University
15


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.
The Hashemite University

16


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.
The Hashemite University

17


Example I: (Counter-Controlled
Repetition)



Counter-controlled repetition




Definite repetition




Loop repeated until counter reaches a
certain value.
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.
The Hashemite University

18


1
2
3
4

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33


// Fig. 2.7: fig02_07.cpp
// Class average program with counter-controlled repetition
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int total,
gradeCounter,
grade,
average;

//
//
//
//

sum of grades
number of grades entered
one grade
average of grades

// initialization phase
total = 0;
gradeCounter = 1;
// processing phase
while ( gradeCounter <= 10 ) {
cout << "Enter grade: ";
cin >> grade;

total = total + grade;
gradeCounter = gradeCounter + 1;
}

// clear total
// prepare to loop

//
//
//
//
//

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

loop 10
prompt for input
input grade
add grade to total
increment counter

// termination phase
average = total / 10;
// integer division
cout << "Class average is " << average << endl;
return 0;
}


The
Hashemite University
// indicate program ended
successfully

19


Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Class

grade: 98
grade: 76
grade: 71
grade: 87
grade: 83
grade: 90
grade: 57
grade: 79
grade: 82

grade: 94
average is 81

The Hashemite University

20


Example II: (Sentinel-Controlled
Repetition)


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)
The Hashemite University

21


1
2
3

// Fig. 2.9: fig02_09.cpp
// Class average program with sentinel-controlled repetition.
#include <iostream>

4
5
6
7

using std::cout;
using std::cin;
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
18
19
20

int total,
gradeCounter,
grade;
double average;

21
22
23
24

// initialization phase
total = 0;
gradeCounter = 0;

25
26
27
28

// processing phase

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

29
30

//
//
//
//

Data type double used to represent
decimal numbers.

sum of grades
number of grades entered
one grade
number with decimal point for average

The Hashemite University
while ( grade != -1 ) {

22


31
total = total + grade;
32
gradeCounter = gradeCounter + 1;
33

cout << "Enter grade, -1 to end: ";
34
cin >> grade;
35
}
36
37
// termination phase
38
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
}
setiosflags(ios::fixed | ios::showpoint) - stream
44
else
static_cast<double>()
- treats total as a
manipulator
45
cout << "No grades were
entered" << endl;
double

temporarily.
46
47
return 0;
// indicateios::fixed
program ended successfully
output numbers with a fixed number of decimal
48 }Required because dividing two integers truncates the

remainder.

points.

ios::showpoint - forces decimal point and trailing zeros, even if

EntergradeCounter
grade, -1 to end:
is an75int,unnecessary:
but it gets promoted
tosetprecision(2)
- prints only two digits
66 printed
as 66.00
Enter grade, -1 to end: 94
past decimal point.
Enterdouble.
grade, -1 to end: 97
Enter grade, -1 to end: 88
| - separates multiple option.
Enter grade, -1 to end: 70

Programs that use this must include <iomanip>
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50

The Hashemite University

23


Example III: Nested control
structures


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 countercontrolled 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.

The Hashemite University

24


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
23

if ( result == 1 )
passes = passes + 1;

// if/else nested in while

The Hashemite University

25


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×