Sei sulla pagina 1di 88

1

Chapter 2 - Control Structures


Outline
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
2.10

2.11
2.12
2.13
2.14
2.15

Introduction
Algorithms
Pseudocode
Control Structures
The if Selection Structure
The if/else Selection Structure
The while Repetition Structure
Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)
Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 2 (Sentinel-Controlled Repetition)
Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 3 (Nested Control Structures)
Assignment Operators
Increment and Decrement Operators
Essentials of Counter-Controlled Repetition
The for Repetition Structure
Examples Using the for Structure

2000 Prentice Hall, Inc. All rights reserved.

Chapter 2 - Control Structures


Outline

2.16
2.17
2.18
2.19
2.20
2.21

The switch Multiple-Selection Structure


The do/while Repetition Structure
The break and continue Statements
Logical Operators
Confusing Equality (==) and Assignment (=) Operators
Structured-Programming Summary

2000 Prentice Hall, Inc. All rights reserved.

2.1 Introduction
Before writing a program:
Have a thorough understanding of problem
Carefully plan your approach for solving it

While writing a program:

Know what building blocks are available


Use good programming principles

2000 Prentice Hall, Inc. All rights reserved.

Fundamental Building Blocks of Programs


THERE ARE TWO BASIC ASPECTS of
programming:
data and instructions.

To work with data


you need to understand variables and types

To work with instructions


you need to understand control structures and subroutines.
You'll spend a large part of the course becoming familiar
with these concepts

Ref: http://math.hws.edu/javanotes/c1/s4.html

2000 Prentice Hall, Inc. All rights reserved.

A few good programming practices


Be consistent with formatting. A well formtated piece of code
Useintmain()
proper spacing and indentation
There's
nothing worse than code that is difficult to read because it is
{
poorly formatted.

if(num1==num2)

Be consistent with naming conventions

cout<<num1<<"isequalto"<<num2<<endl;
Chose
one naming style and stick with it

if(num1!=num2)
Use global
variables sparingly
cout<<num1<<"isnotequalto"<<num2<<endl;
Avoid
them as much as possible
}
Comment.
Add comments to your code in plain English
that describe both
what the
code ispiece
doing
and why you
A poorly
formtated
of code
decided to do it one way and not another way Ref:
intmain()
Check return values for error conditions
{if(num1==num2)
Provide useful error messages.
cout<<num1<<"isequalto"<<num2<<endl;
Recover (or fail) gracefully.
if(num1!=num2)
http://www.kmoser.com/articles/Good_Programming_Practice
cout<<num1<<"isnotequalto
" <<num2<<endl;}
s.php

2000 Prentice Hall, Inc. All rights reserved.

2.2

Algorithms

All computing problems


can be solved by executing a series of actions in a specific
order

Algorithm
A procedure determining the
Actions to be executed
Order in which these actions are to be executed

Program control

Specifies the order in which statements are to executed

2000 Prentice Hall, Inc. All rights reserved.

The Algorithm to Start the Car


1.Insert the key
2.Make sure car is in neutral gear
3.Press the gas pedal/ (Accelerator)
4.Turn the key to the start position
5.If the engine starts in 6 seconds
1.Release the key to the ignition position

6.Else if the engine does not start in 6 seconds


1.Release the key and gas pedal
2.Wait for 10 seconds , and repeat the steps 3 6, but no more
than 5 times

7. If the car does not start

1.Call the workshop


2000 Prentice Hall, Inc. All rights reserved.

2.3

Pseudocode

Pseudocode

Artificial, informal language used to develop algorithms


Similar to everyday English
Not actually executed on computers
Allows us to think out a program before writing the code
for it
Easy to convert into a corresponding C++ program
Consists only of executable statements
Example:
If students grade is greater than or equal to 60

Print "Passed

2000 Prentice Hall, Inc. All rights reserved.

2.4

Control Structures

Sequential execution
Statements executed one after the other in the order written

Transfer of control
When the next statement executed is not the next one in
sequence

Bohm and Jacopini: all programs written in terms


of 3 control structures
Sequence structure
Built into C++. Programs executed sequentially by default.

Selection structures
C++ has three types - if, if/else, and switch

Repetition structures

C++ has three types - while, do/while, and for


2000 Prentice Hall, Inc. All rights reserved.

10

2.4

Control Structures

C++ keywords
Cannot be used as identifiers or variable names.

C++ Keywords
Keywordscommontothe
CandC++programming
languages
auto
continue
enum
if
short
switch
volatile

break
default
extern
int
signed
typedef
while

case
do
float
long
sizeof
union

char
double
for
register
static
unsigned

const
else
goto
return
struct
void

C++onlykeywords
asm
delete
inline
private
static_cast
try
wchar_t

bool
dynamic_cast
mutable
protected
template
typeid

catch
class
explicit false
namespacenew
public
reinterpret_cast
this
throw
typename using

2000 Prentice Hall, Inc. All rights reserved.

const_cast
friend
operator

true
virtual

Flowchart

2.4

Control Structures

Graphical representation of an algorithm


Drawn using certain special-purpose symbols connected by
arrows called flowlines.
Rectangle symbol (action symbol)
Indicates any type of action.

Oval symbol
indicates beginning or end of a program, or a section of code
(circles).

Diamond symbol (decision symbol)


indicates decision is to be made

single-entry/single-exit control structures

Connect exit point of one control structure to entry point of


the next (control-structure stacking).
Makes programs easy to build.
2000 Prentice Hall, Inc. All rights reserved.

11

12

2.5

The if Selection Structure

Selection structure
used to choose among alternative courses of action
Pseudocode example:
If students grade is greater than or equal to 60
Print Passed

If the condition is true


print statement executed and program goes on to next
statement

If the condition is false


print statement is ignored and the program goes onto the next
statement

Indenting makes programs easier to read

C++ ignores whitespace characters


2000 Prentice Hall, Inc. All rights reserved.

13

2.5

The if Selection Structure

Translation of pseudocode statement into C++:


if ( grade >= 60 )
cout << "Passed";

Diamond symbol (decision symbol)


indicates decision is to be made
Contains an expression that can be true or false.
Test the condition, follow appropriate path

if structure is a single-entry/single-exit structure

2000 Prentice Hall, Inc. All rights reserved.

14

2.5

The if Selection Structure

Flowchart of pseudocode statement

A decision can be made on


any expression.
grade >= 60

true

print Passed

zero - false
nonzero - true
Example:

false

2000 Prentice Hall, Inc. All rights reserved.

3 - 4 is true

15

2.6

The if/else Selection Structure

if
Only performs an action if the condition is true

if/else
A different action is performed when condition is true and
when condition is false

Psuedocode
if students grade is greater than or equal to 60
print Passed
else
print Failed

C++ code

if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
2000 Prentice Hall, Inc. All rights reserved.

16

2.6

The if/else Selection Structure


false

grade >= 60

print Failed

C++ code

if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";

2000 Prentice Hall, Inc. All rights reserved.

true
print Passed

17

2.6

The if/else Selection Structure


false

grade >= 60

print Failed

true
print Passed

Ternary conditional operator (?:)


Takes three arguments (condition, value if true, value if false)

Our pseudocode could be written:

cout << ( grade >= 60 ? Passed : Failed );

2000 Prentice Hall, Inc. All rights reserved.

18

Ternary conditional operator


Nested if/else structures
Test for multiple cases by placing if/else selection
structures inside if/else selection structures.
if students grade is greater than or equal to 90
Print A
else
if students grade is greater than or equal to 80
Print B
else
if students grade is greater than or equal to 70
Print C
else
if students grade is greater than or equal to 60
Print D
else
Print F

Once a condition is met, the rest of the statements are skipped


2000 Prentice Hall, Inc. All rights reserved.

19

2.6

The if/else Selection Structure

Compound statement:
Set of statements within a pair of braces
Example:
if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
Without the braces,
cout << "You must take this course again.\n";
would be automatically executed

Block

Compound statements with declarations


2000 Prentice Hall, Inc. All rights reserved.

20

2.6

The if/else Selection Structure

Syntax errors
Errors caught by compiler

Logic errors
Errors which have their effect at execution time

Non-fatal logic errors


program runs, but has incorrect output
Fatal logic errors
program exits prematurely

2000 Prentice Hall, Inc. All rights reserved.

The switch Multiple-Selection


Statement
switch
Useful when a variable or expression is tested for all the values it
can assume and different actions are taken

Format
Series of case labels and an optional default case

switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
break; // exits from statement
2000 Prentice Hall, Inc. All rights reserved.

21

Same actions taken for two cases


switch ( value ){
case '1':
case '2':
actions /* one or more statements */
break;
case '3':
case '4':
actions /* one or more statements */
break;

default:
actions
break;
}
2000 Prentice Hall, Inc. All rights reserved.

/* one or more statements */

22

2.16 The switch Multiple-Selection Structure


switch
Useful when variable or expression is tested for multiple values
Consists of a series of case labels and an optional default case

case a

true

case a action(s)

break

case b action(s)

break

case z action(s)

break

false
case b

true

false
.
.
.

case z

true

false

default action(s)
2000 Prentice Hall, Inc. All rights reserved.

2.7

The while Repetition Structure

Repetition structure
Programmer specifies an action to be repeated while some
condition remains true
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.

Example

int product = 2;
while ( product <= 1000 )
product = 2 * product;

2000 Prentice Hall, Inc. All rights reserved.

24

25

2.7

The while Repetition Structure

Flowchart of while loop

product <= 1000

false

2000 Prentice Hall, Inc. All rights reserved.

true
product = 2 * product

2.8

Formulating Algorithms (CounterControlled 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.

2000 Prentice Hall, Inc. All rights reserved.

26

2.8

Formulating Algorithms (CounterControlled Repetition)

27

Pseudocode for example:


Set total to zero

total = 0

Set grade counter to one

gradeCounter = 1

While grade counter is less than or equal to ten while (gradeCounter 10)
Input the next grade

input grade

Add the grade into the total

total = total + grade


gradeCounter =
gradeCounter + 1

Add one to the grade counter

Set the class average to the total divided by ten average = total / 10
Print the class average

Print average

Following is the C++ code for this example

2000 Prentice Hall, Inc. All rights reserved.

1 // Fig. 2.7: fig02_07.cpp


2 // Class average program with counter-controlled repetition
3 #include <iostream.h>
4

9 int main()
10 {
11
12

int total,
// sum of grades
gradeCounter, // number of grades entered

13
14
16
17
18

grade,
// one grade
average;
// average of grades
// initialization phase
total = 0;
// clear total
gradeCounter = 1;
// prepare to loop

21

while ( gradeCounter <= 10 ) {

20

// processing phase
cout << "Enter grade: ";
cin >> grade;

// prompt for input


// input grade

24
total
25

total = total + grade;

// add grade to

gradeCounter = gradeCounter + 1;

// increment

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

33 }

// indicate program ended successfully

2000 Prentice Hall, Inc. All rights reserved.

1. Initialize Variables
2. Execute Loop
3. Output results

The counter gets incremented each time


the loop executes. Eventually, the
counter causes the loop to end.

// loop 10 times

22
23

28
29
30
31
32

Outline

28

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

2000 Prentice Hall, Inc. All rights reserved.

Outline
Program Output

29

2.9 Formulating Algorithms with Top-Down,


Stepwise Refinement (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 is inputted
Sentinel value chosen so it cannot be confused with a regular
input (such as -1 in this case)

2000 Prentice Hall, Inc. All rights reserved.

30

2.9 Formulating Algorithms with Top-Down,


Stepwise Refinement (Sentinel-Controlled
Repetition)

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 variables
Input, sum and count the quiz grades
Calculate and print the class average

2000 Prentice Hall, Inc. All rights reserved.

31

2.9

Formulating Algorithms with Top-Down,


Stepwise Refinement

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.
Recall the program
Refine the initialization phase from
to control average
Initialize variables
grade of the class
to
Initialize total to zero
total = 0
Initialize counter to zero
gradeCounter = 1

2000 Prentice Hall, Inc. All rights reserved.

32

2.9

Formulating Algorithms with Top-Down,


Stepwise Refinement

Refine

33

Processing step

Input, sum and count the quiz grades


to

input grade
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel while continue
Add this grade into the running total
total = total + grade
Add one to the grade counter
gradeCounter = gradeCounter + 1
input grade
Input the next grade (possibly the sentinel)

Refine

Termination step

Calculate and print the class average


to
grade ! =0 ?
If the counter is not equal to zero
average = total / 10
Set the average to the total divided by the counter
Print the average
Print average
Else
Print No grades were entered
2000 Prentice Hall, Inc. All rights reserved.

1 // Fig. 2.9: fig02_09.cpp


2 // Class average program with sentinel-controlled
repetition.
3 #include <iostream.h>
4 #include <iomanip.h>
5 int main()
Data type float used to represent
6 {
decimal numbers.
7
int total,
// sum of grades
8
gradeCounter, // number of grades entered
9
grade;
// one grade
10
float average;
// number with decimal point for
average
11
12
// initialization phase
13
total = 0;
14
gradeCounter = 0;
15
16
// processing phase
17
cout << "Enter grade, -1 to end: ";
18
cin >> grade;
19
20
while ( grade != -1 ) {
21
total = total + grade;
22
gradeCounter = gradeCounter + 1;
23
24
25

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


cin >> grade;

}
2000 Prentice Hall, Inc. All rights reserved.

Outline
1. Initialize Variables
2. Get user input
2.1 Perform Loop

34

Outline

26
27
28
29
30
31

35

// termination phase
if ( gradeCounter != 0 ) {
3. Calculate Average
average = (float )( total ) / gradeCounter;
cout << "Class average is " << setprecision( 2 )
<< setiosflags( iostream::fixed | iostream::showpoint )

32
33

<< average << endl;


}

3.1 Print Results

34
else
35
cout << "No grades were
entered" << endl;| iostream::showpoint) - stream
=-iostream::fixed
setprecision(2) - prints only two digits
36
(float)(total) - treats totalmanipulator
as a double
decimal point.
37
return 0;
// indicate program ended past
successfully
temporarily.
38 }

iostream::fixed
- output
numbers
withinclude
a fixed number of
Programs
that use
this must
Required
because
two75
integers
truncates the
Enter
grade,
-1dividing
to end:
decimal
points.
<iomanip.h>
remainder.
Enter
grade, -1 to end: 94
Enter grade, -1 to end: 97
iostream::showpoint - forces decimal point and trailing zeros,
Enter
grade,
-1
to
end:
88
gradeCounter is an int, but it gets
to
evenpromoted
if unnecessary:
66 printed as 66.00
Enter
grade,
-1
to
end:
70
double.
Enter grade, -1 to end: 64
Program Output
| - separates multiple option.
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50

2000 Prentice Hall, Inc. All rights reserved.

36

Before you start coding


Ensure your algorithm is correct.

How is that done?

One way is to Dry Run your algorithm.

2000 Prentice Hall, Inc. All rights reserved.

37

Dry Run
a dry run is a mental run of an algorithm,
sometimes expressed in pseudocode, where the
computer scientist examines the algorithm's
procedures one step at a time.
(Source: Wikipedia)

Use pen and paper to keep track of variable values


during a dry run.

2000 Prentice Hall, Inc. All rights reserved.

2.9

Formulating Algorithms with Top-Down,


Stepwise Refinement

Input the first grade


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)

2000 Prentice Hall, Inc. All rights reserved.

38

2.10 Nested control structures


Problem:

Outline

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.
2000 Prentice Hall, Inc. All rights reserved.

39

2.10 Nested control structures

Outline

Top level outline:


Analyze exam results and decide if tuition should be raised

First Refinement:
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition
should be raised

Refine

Initialize variables
to
passes = 0
Initialize passes to zero
failures = 0
Initialize failures to zero
Initialize student counter to one studentCounter = 1
2000 Prentice Hall, Inc. All rights reserved.

40

2.10 Nested control structures

Outline

41

Refine
Input the ten quiz grades and count passes and failures
to

While student counter is less than or equal to ten while ( studentCounter 10 )


input result
Input the next exam result
If the student passed
If (result = 1)
passes = passes + 1
Add one to passes
Else
Else
failures = failures + 1
Add one to failures
studentCounter =studentCounter+ 1
Add one to student counter

Refine
Print a summary of the exam results and decide if tuition should be raised
to

Print the number of passes


Print the number of failures
If more than eight students passed
Print Raise tuition
2000 Prentice Hall, Inc. All rights reserved.

Print passes
Print failures
if passes > 8
Print Raise tuition

1 // Fig. 2.11: fig02_11.cpp


2 // Analysis of examination results
3 #include <iostream.h>

1. Initialize variables

4 int main()
5 {
6

// initialize variables in declarations

int passes = 0,

// number of passes

failures = 0,

// number of failures

studentCounter = 1,

// student counter

result;

// one exam result

10
11
12

// process 10 students; counter-controlled loop

13

while ( studentCounter <= 10 ) {

14

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

15

cin >> result;

16
17

if ( result == 1 )

18

// if/else nested in while

passes = passes + 1;

19

else

20

failures = failures + 1;

21
22

studentCounter = studentCounter + 1;

23

Outline

2000 Prentice Hall, Inc. All rights reserved.

2. Input data and


count passes/failures

42

Outline

24
25

// termination phase

26

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

27

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

3. Print results

28
29

if ( passes > 8 )

30

cout << "Raise tuition " << endl;

31
32

return 0;

// successful termination

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

1
1
1
1
2
1
1
1
1
1

2000 Prentice Hall, Inc. All rights reserved.

Program Output

43

44

2.11 Assignment Operators


Assignment expression abbreviations
c = c + 3; can be abbreviated as c += 3; using the
addition assignment operator

Statements of the form


variable = variable operator expression;

can be rewritten as
variable operator= expression;

Examples of other assignment operators include:

d
e
f
g

-=
*=
/=
%=

4
5
3
9

2000 Prentice Hall, Inc. All rights reserved.

(d
(e
(f
(g

=
=
=
=

d
e
f
g

*
/
%

4)
5)
3)
9)

45

2.12 Increment and Decrement Operators


Increment operator (++) - can be used instead of
c += 1
Decrement operator (--) - can be used instead of
c -= 1
Preincrement
When the operator is used before the variable (++c or c)
Variable is changed, then the expression, it is in, is evaluated.

Posincrement
When the operator is used after the variable (c++ or c--)
Expression the variable is in executes, then the variable is changed.

If c = 5, then

cout << ++c; prints out 6 (c is changed before cout is


executed)
cout << c++; prints out 5 (cout is executed before the
increment. c now has the value of 6)
2000 Prentice Hall, Inc. All rights reserved.

46

2.12 Increment and Decrement Operators

When Variable is not in an expression


Preincrementing and postincrementing have the
same effect.
++c;
If c was originally 5
cout << c;

and
c++;
cout << c;

have the same effect.

2000 Prentice Hall, Inc. All rights reserved.

What will be Output ?


6

Some Examples Nested Loop

- Nested While Loop


1. Write a program to print a triangle of *

47

*
**
***
****
*****

Use 2 counters, one each for row counter


and column counter
Each time the columns will start from one, so the counter for
column must be initialized inside the first while loop
The row counter and column count have be increment inside first
while and outside second while (except the column counter)

2. Practice questions
- print a square of * using nested while loop, rows and
column are given.
- Print a triangle as above but use sentinel repetition
control

2000 Prentice Hall, Inc. All rights reserved.

Some Examples - Operators

48

c = (a++) + (b++)
#include<iostream.h>
c = a + b = 5 + 6 = 11 the summation result is stored
#include<conio.h>
a++ = 6
in c before the post increments
void main(){
b++ = 7
int a = 5; int b= 6;
int c = (a++) + (b++); clrscr();
Screen Output
cout<<"\na = "<<a;
a=6
cout<<"\nb = "<<b;
b=7
cout<<"\nc = "<<c;
c = 11

int x=4; int y=4;


int z = (x++) - (--y);
cout<<"\n\nx = "<<x;
cout<<"\ny = "<<y;
cout<<"\nz= "<<z;

x=5
y=3
z =1

z = (x++) (--y)
--y = 3
z=43=1

x++ = 5
2000 Prentice Hall, Inc. All rights reserved.

Some Examples
int k; float f;
x = 5; y = 3;
cout<<"\n\nx/y = "<<x/y;
f = x/y;
cout<<"\n\nf = x/y = "<<f;
k = (float)(x/y);
cout<<"\n\nk = (float)(x/y) = "<<k;
f = (float)(x/y);
cout<<"\n\nf = (float)(x/y)= "<<f;
cout<<"\n\n(float)(x/y) = "<<(float)(x/y);
cout<<"\n\n(float)x /y = "<<(float)x /y;
cout<<"\n\n1.5 /3 = "<< 1.5/3;
cout<<"\n\n1/3.0 = "<< 1/3.0;
getch();
}

2000 Prentice Hall, Inc. All rights reserved.

49

Screen Output
x/y = 1
f = x/y = 1
k = (float)(x/y) = 1
f = (float)(x/y) = 1
(float)(x/y) = 1
(float)x /y = 1.6666667
1.5/3 = 0.5
1/3.0 = 0.333333

2.13 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.
Body (optional)

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

}
2000 Prentice Hall, Inc. All rights reserved.

50

2.13 Essentials of Counter-Controlled


Repetition
The declaration
int counter = 1;

Names counter
Declares counter to be an integer
Reserves space for counter in memory
Sets counter to an initial value of 1

2000 Prentice Hall, Inc. All rights reserved.

51

52

2.14 The for Repetition Structure


The general format when using for loops is
for ( initialization; LoopContinuationTest;
increment )

statement

Example:
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;

Prints the integers from one to ten

2000 Prentice Hall, Inc. All rights reserved.

No
semicolon
after last
statement

53

2.14 The for Repetition Statement

forkeyword Controlvariablename

Finalvalueofthe
controlvariableforthe
conditionistrue

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


Initial value of control variable

Incrementofcontrolvari

Loop-continuation condition

2000 Prentice Hall, Inc. All rights reserved.

54

2.14 The for Repetition 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;

2000 Prentice Hall, Inc. All rights reserved.

55

2.14 The for Repetition Statement


Format when using for loops
for ( initialization; loopContinuationTest; increment )

statement
----------------------------------------------------------------------------------------

for ( initialization; loopContinuationTest; increment ) {

statement1
statement2
..
statementN
}

No
semicolon
(;) after last
expression

Example:
for( int counter = 1; counter <= 10; counter++ )
cout<<\n<< counter;

Prints the integers from one to ten


2000 Prentice Hall, Inc. All rights reserved.

56

Recap:

The while Repetition Structure

Flowchart of while loop

product <= 1000

false

2000 Prentice Hall, Inc. All rights reserved.

true
product = 2 * product

57

The for Statement :

Establish initial
value of control
variable

counter
1
counter = 1

counter <= 10
Determine if final
value of control
variable has been
reached

false

true

Cout<<\n <<counter ;

Body of loop
(this may be many
statements)
counter = 1

counter++
Increment
the control
variable

Initialization placed before


the while statement

while Statement
counter <= 10

true

Cout<<\n <<counter ;
counter++

false
2000 Prentice Hall, Inc. All rights reserved.

Counter integrated into the


body of while statement

Outline

fig04_02.c

2000 Prentice Hall, Inc. All rights reserved.

58

2.14 The for Statement : Notes and


Observations
Arithmetic expressions
Initialization, loop-continuation, and increment can contain
arithmetic expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y / x )

is equivalent to
for ( j = 2; j <= 80; j += 5 )

Notes about the for statement:


"Increment" may be negative (decrement)
If the loop continuation condition is initially false
The body of the for statement is not performed
Control proceeds with the next statement after the for statement

Control variable

Often printed or used inside for body, but not necessary


2000 Prentice Hall, Inc. All rights reserved.

59

60

The for Statement :


Establish initial
value of control
variable

counter
1
counter = 1

counter <= 10

Determine if final
value of control
variable has been
reached

false

2000 Prentice Hall, Inc. All rights reserved.

true

Cout<<\n <<counter ;

Body of loop
(this may be many
statements)

counter++
Increment
the control
variable

61

2.15 Examples Using the for Structure


Program to sum the even numbers from 2 to 100
1

// Fig. 2.20: fig02_20.cpp

// Summation with for

#include <iostream.h>

7
8

int main()

10

int sum = 0;

11
12
13

for ( int number = 2; number <= 100; number += 2 )


sum += number;

14
15

cout << "Sum is " << sum << endl;

16
17

return 0;

18 }

Sum is 2550
2000 Prentice Hall, Inc. All rights reserved.

Outline

fig04_06.c (Part 1 of 2)

2000 Prentice Hall, Inc. All rights reserved.

62

27

return 0; /* indicate program ended successfully */

28
29 } /* end function main */

Outline
fig04_06.c (Part 2 of 2)

04 character places

Program Output

21 character places

Year
1
2
3
4
5
6
7
8
9
10

Amount on deposit
1050.00
1102.50
1157.63
1215.51
1276.28
1340.10
1407.10
1477.46
1551.33
1628.89

2000 Prentice Hall, Inc. All rights reserved.

63

64

2.17 The do/while Repetition Structure


The do/while repetition structure is similar to the
while structure,
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

All actions are performed at least once.


2000 Prentice Hall, Inc. All rights reserved.

action(s)

true
condition
false

2.17 The dowhile Repetition Statement


Flowchart of the dowhile repetition statement

action(s)

true
condition

false

2000 Prentice Hall, Inc. All rights reserved.

2.17 COMPARISON: The while Repetition


Statement
Flowchart of the while repetition statement

action(s)

condition
true

false

2000 Prentice Hall, Inc. All rights reserved.

67

2.18 The break and continue Statements


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

2000 Prentice Hall, Inc. All rights reserved.

1 2 3 4
Broke out of loop at x == 5

2000 Prentice Hall, Inc. All rights reserved.

69

2.18 The break and continue Statements


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
In while and do/while, the loop-continuation test is
evaluated immediately after the continue statement is
executed
In the for structure, the increment expression is executed,
then the loop-continuation test is evaluated

2000 Prentice Hall, Inc. All rights reserved.

fig04_12.c

1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5

2000 Prentice Hall, Inc. All rights reserved.

71

2.19 Logical Operators


&& (logical AND)
Returns true if both conditions are true

|| (logical OR)
Returns true if either of its conditions are true

! (logical NOT, logical negation)


Reverses the truth/falsity of its condition
Returns true when its condition is false
Is a unary operator, only takes one condition

Logical operators used as conditions in loops

Expression
true && false
true || false
!false
2000 Prentice Hall, Inc. All rights reserved.

Result
false
true
true

2.20 Confusing Equality (==) and


Assignment (=) Operators
These errors are damaging because they do not
ordinarily cause syntax errors.
Recall that any expression that produces a value can be used in
control structures. Nonzero values are true, and zero values
are false

Example:
if ( payCode == 4 )
cout << "You get a bonus!" << endl;

Checks the paycode, and if it is 4 then a bonus is awarded

If == was replaced with =


if ( payCode = 4 )
cout << "You get a bonus!" << endl;

Sets paycode to 4
4 is nonzero, so the expression is true and a bonus is awarded,
regardless of paycode.
2000 Prentice Hall, Inc. All rights reserved.

72

2.20 Confusing Equality (==) and


Assignment (=) Operators
Lvalues
Expressions that can appear on the left side of an equation
Their values can be changed
Variable names are a common example (as in x = 4;)

Rvalues
Expressions that can only appear on the right side of an
equation
Constants, such as numbers (i.e. you cannot write 4 = x;)

Lvalues can be used as rvalues, but not vice versa

2000 Prentice Hall, Inc. All rights reserved.

73

Operator precedence examples

2000 Prentice Hall, Inc. All rights reserved.

74

2.16 The switch Multiple-Selection


Statement
switch
Useful when a variable or expression is tested for all the
values it can assume and different actions are taken

Format
Series of case labels and an optional default case
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}

break; exits from statement


2000 Prentice Hall, Inc. All rights reserved.

75

76

Same actions taken for two cases


switch ( value ){
case '1':
case '2':
actions /* one or more statements */
break;
case '3':
case '4':
actions /* one or more statements */
break;

default:
actions
break;
}
2000 Prentice Hall, Inc. All rights reserved.

/* one or more statements */

77

2.16 The switch Multiple-Selection Structure


switch
Useful when variable or expression is tested for multiple values
Consists of a series of case labels and an optional default case
case a

true

case a action(s)

break

case b action(s)

break

case z action(s)

break

false

case b

true

false
.
.
.

case z

true

false

default action(s)

2000 Prentice Hall, Inc. All rights reserved.

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
34

78

// Fig. 2.22: fig02_22.cpp


// Counting letter grades
#include <iostream.h>

1. Initialize variables
2. Input data
int main()
{
int grade,
aCount
bCount
cCount
dCount
fCount

=
=
=
=
=

0,
0,
0,
0,
0;

//
//
//
//
//
//

one grade
number of
number of
number of
number of
number of

A's
B's
C's
D's
F's

cout << "Enter the letter grades." << endl


<< "Enter the EOF character to end input." << endl;
while ( ( grade = cin.get() ) != EOF ) {
switch ( grade ) {

Notice how the case statement is used


// switch nested in while

case 'A': // grade was uppercase A


case 'a': // or lowercase a
++aCount;
break; // necessary to exit switch
case 'B': // grade was uppercase B
case 'b': // or lowercase b
++bCount;
break;
2000 Prentice Hall, Inc. All rights reserved.

2.1 Use switch loop to


update count

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

79

case 'C': // grade was uppercase C


case 'c': // or lowercase c
++cCount;
break;

2.1 Use switch loop to


count

case 'D': // grade was uppercase D


break causes switch to end and
update
case 'd': // or lowercase d
the program continues with the first
++dCount;
break;
statement after the switch structure.

3. Print results

case 'F': // grade was uppercase F


case 'f': // or lowercase f
++fCount;
break;
case '\n': // ignore newlines,
case '\t': // tabs,
case ' ': // and spaces in input
Notice
break;
default:
cout <<
<<
break;

the default statement.

// catch all other characters


"Incorrect letter grade entered."
" Enter a new grade." << endl;
// optional

}
}

cout <<
<<
<<
<<
<<
<<

"\n\nTotals for each letter grade are:"


"\nA: " << aCount
"\nB: " << bCount
"\nC: " << cCount
"\nD: " << dCount
"\nF: " << fCount << endl;

return 0;
2000 Prentice Hall, Inc. All rights reserved.

80
Enter the letter grades.
Enter the EOF character to end input.
a
B
c
C
A
d
f
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
b
Totals for each letter grade are:
A: 3
B: 2
C: 3
D: 2
F: 1

2000 Prentice Hall, Inc. All rights reserved.

Program Output

81

2.17 The do/while Repetition Structure


The do/while repetition structure is similar to the
while structure,
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

All actions are performed at least once.


2000 Prentice Hall, Inc. All rights reserved.

action(s)

true
condition
false

2.17 The dowhile Repetition Statement


Flowchart of the dowhile repetition statement

action(s)

true
condition

false

2000 Prentice Hall, Inc. All rights reserved.

2.17 COMPARISON: The while Repetition


Statement
Flowchart of the while repetition statement

action(s)

condition
true

false

2000 Prentice Hall, Inc. All rights reserved.

2.21 Structured-Programming Summary


Structured programming
Programs are easier to understand, test, debug and, modify.

Rules for structured programming


Only single-entry/single-exit control structures are used
Rules:

1) Begin with the simplest flowchart.


2) Any rectangle (action) can be replaced by two rectangles
(actions) in sequence.
3) Any rectangle (action) can be replaced by any control
structure (sequence, if, if/else, switch, while, do/while or for).
4) Rules 2 and 3 can be applied in any order and multiple times.

2000 Prentice Hall, Inc. All rights reserved.

84

2.21 Structured-Programming Summary


Representation of Rule 3 (replacing any rectangle with a control structure)

Rule 3

Rule 3

2000 Prentice Hall, Inc. All rights reserved.

Rule 3

85

2.21 Structured-Programming Summary


All programs can be broken down into
Sequence
Selection
if, if/else, or switch
Any selection can be rewritten as an if statement

Repetition

while, do/while or for


Any repetition structure can be rewritten as a while
statement

2000 Prentice Hall, Inc. All rights reserved.

86

87

Nested for loop

for(num2 = 0; num2 <= 3; num2++)


{
for(num1 = 0; num1 <= 2; num1++)
{
cout<< num2<< " " << num1<< endl;
}
}

http://mathbits.com/mathbits/compsci/looping/nested.htm
2000 Prentice Hall, Inc. All rights reserved.

88

Nested for loop

for(num2 = 0; num2 <= 3; num2++)


{
for(num1 = 0; num1 <= 2; num1++)
{
cout<< num2<< " " << num1<< endl;
}
}

http://mathbits.com/mathbits/compsci/looping/nested.htm
2000 Prentice Hall, Inc. All rights reserved.

Potrebbero piacerti anche