Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 6...

94
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 6 Control Structures Starting Out with Games & Graphics in C++ Tony Gaddis

Transcript of Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 6...

Addison Wesley is an imprint of

© 2010 Pearson Addison-Wesley. All rights reserved.

Chapter 6Control Structures

Starting Out with

Games & Graphics in C++

Tony Gaddis

Copyright © 2010 Pearson Addison-Wesley

6.1 Introduction

1-2

Concept:

Control structures affect the order in which statements execute. There are three main types of control structures: sequence, decision, and repetition.

Copyright © 2010 Pearson Addison-Wesley

6.1 Introduction

• A control structure determines the order in which a set of statements execute

• In the 1960’s a group of mathematicians proved that only three control structures are needed to write any type of program, they are:– The sequence structure– The decision structure– The repetition structure

• The simplest of these structures is the sequence structure, which is a set of statements that execute in the order they appear

1-3

Copyright © 2010 Pearson Addison-Wesley

6.1 Introduction

• For an example of a sequence structure, look at the following DarkGDK function:

1-4

• The statements inside the function are a sequence structure– They execute in the order they are written from top to

bottom

Copyright © 2010 Pearson Addison-Wesley

6.1 Introduction• Flowcharts, planning tools that

programmers use to design a program’s logic

• Terminals, elliptical symbols at the top and bottom of the flowchart that mark the algorithm’s start and end points

• The symbols that appear between the terminals are the steps taken in the algorithm

• The steps are connected by arrows that represent the flow of execution

• The flowchart in Figure 6-1 depicts a sequence structure because the steps are taken one after another, from the beginning to the end

1-5

Figure 6-1 Flowchart for a sequence structure

Copyright © 2010 Pearson Addison-Wesley

6.1 Introduction

• Some problems simply cannot be solved by performing a set of ordered steps, one after another

• In some programs, a set of statements must be executed only under certain circumstances

• If those circumstances do not exist, the statements should be skipped

1-6

• Consider a company payroll program that determines whether an employee has worked overtime– If the employee has worked more than 40 hours, he or she gets paid

a higher wage for the hours over 40– Otherwise, the overtime calculation should be skipped

• Solving this kind of problem requires a decision structure

Copyright © 2010 Pearson Addison-Wesley

6.1 Introduction

• Suppose the same payroll program calculates pay for all employees– This means that it has to perform the same

steps for each employee

• Solving this kind of problem requires a repetition structure, which is also known as a loop, which is a structure that repeats a set of statements as many times as necessary

1-7

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

1-8

Concept:

The if statement is used to create a decision structure, which allows a program to have more than one path of execution. The if statement causes one or more statements to execute only when a Boolean expression is true.

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• In a decision structure’s simplest form– A specific action is performed

only if a certain condition exists– If the condition does not exist,

the action is not performed• A single alternative, as shown

in Figure 6-2, provides only one alternative path of execution– If the condition in the diamond

symbol is true– We take the alternate path– Otherwise, we exit the

structure

1-9

Figure 6-2 A simple decision, structure, also

known as a single alternative decision

structure

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

1-10

• The diamond symbol indicates some condition that must be tested

• We are determining whether the condition Cold outside is true or false– If this condition is true, the action is

performed– If the condition is false, the action is

skipped• The action is conditionally executed

because it is performed only when a certain condition is true

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• Here is the general format of the if statement:

1-11

The statement begins with the word

if

Followed by an expression that

is enclosed in a set of parentheses

Beginning on the next line is a set of

statements enclosed in curly braces

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

1-12

• The expression that appears inside the parentheses is a Boolean expression , which is an expression that can be evaluated as either true or false– When the if statement executes, the Boolean

expression is tested• If it is true, the statements that appear inside

the curly braces are executed

• If it is false the statements inside the curly braces are skipped

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• Although the curly braces are not required when there is only one conditionally executed statement, it is still a good idea to use them, as shown in the following general format:

1-13

• This is a good style of writing if statements because it minimizes errors

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• The value of a Boolean expression can be either true or false• Typically, the Boolean expression that is tested by an if statement

is formed with a relational operator• A relational operator determines whether a specific relationship

exists between two values• Table 6-1 lists the relational operators that are available in C++

1-14

Boolean Expressions and Relational Operators

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• Table 6-2 shows examples of several Boolean expressions that compare the variables x and y

• These expressions determine whether the value is true or false

1-15

Boolean Expressions and Relational Operators

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• Two of the operators, >= and <=, test for more than one relationship– The >= operator

• Determines whether the operand on its left is greater than or equal to the operand on its right

– The <= operator• Determines whether the on its left is less

than or equal to the operand on its right• For example, assume the variable a is

assigned the value 4– All of the following expressions are true:

1-16

The >= and <= Operators

Boolean Expressions and Relational Operators

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• The == operator determines whether the operand on its left is equal to the operand on its right

• If the values of both operands are the same, the expression is true

• Assuming that a is 4– The expression a == 4 is true– The expression a == 2 is false

1-17

Boolean Expressions and Relational Operators

The == Operator

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• The != operator is the not-equal-to operator• It determines whether the operand on the left is not

equal to the operand on the right, which is the opposite of the == operator

• Assuming a is 4, b is 6, and c is 4– Both a != b and b != c are true

• This is because a is not equal to b and b is not equal to c

– However, a != c is false• This is because a is equal to c

1-18

The != Operator

Boolean Expressions and Relational Operators

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• Let’s look at the following example of the if statement:

1-19

Putting It All Together

Figure 6-4 Example decision structure

• This statement uses the > operator to determine whether sales is greater than 50,000

• If the expression sales > 50000 is true– The variable bonus is assigned 500

• If the expression is false– The assignment is skipped

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

1-20

• The following example conditionally executes three statements

Putting It All TogetherFigure 6-5 Example decision structure

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• Notice that in both the previous if statement examples, the conditionally executed statements were indented

• This indentation is not required, but it makes code easier to read and debug

• Most programmers use this style of indentation when writing if statements

1-21

Putting It All Together

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

1-22

Putting It All Together• Let’s look at a complete program that

uses an if statement• The program calculates the average of

three test scores• If the average is greater than 95, it

should display the image stored in a file named Congrats.bmp

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• You can use the relational operators to compare RGB values• For example, suppose you have two DWORD variables named

color1 and color2• The following if statement determines whether they hold the

same value

1-23

Testing Colors

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• If you need to test the color of a specific point on the screen, you can use the dbPoint function to get that point’s color value

• You pass two arguments to the dbPoint function– An X coordinate– A Y coordinate

• The dbPoint function returns a DWORD value containing the color of that point

• The following code shows an example:

1-24

Testing Colors

• The first statement declares a DWORD variable named pixelColor• The second statement calls the dbPoint function to get the color of

the pixel located at (100, 150)• The color of that pixel is returned and assigned to the pixelColor

variable

Copyright © 2010 Pearson Addison-Wesley

6.2 Writing a Decision Structure with the if statement

• The following code shows another example• The code gets the color of the pixel located at (10, 10)• If that pixel’s color is blue, it is changed to red

1-25

Testing Colors

Copyright © 2010 Pearson Addison-Wesley

6.3 The if-else Statement

1-26

Concept:

An if-else statement will execute one block of statements if its Boolean expression is true, or another block if its Boolean expression is false.

Copyright © 2010 Pearson Addison-Wesley

6.3 The if-else Statement

• The dual alternative decision structure has two possible paths of execution– One path is taken if the Boolean expression is

true– The other path is taken if the Boolean

expression is false

1-27

Copyright © 2010 Pearson Addison-Wesley

6.3 The if-else Statement

• Figure 6-7 shows an example flowchart for a dual alternative decision structure

• The decision structure in the flowchart tests the expression temperature < 40– If the expression is true

• The message “A little cold, isn’t it?” is displayed

– If the expression is false

• The message “Nice weather we’re having.” is displayed

1-28

Figure 6-7 A dual alternative decision structure

Copyright © 2010 Pearson Addison-Wesley

6.3 The if-else Statement

• In code we write a dual alternative decision structure as an if-else statement

• Here is the general format of the if-else statement:

1-29

Copyright © 2010 Pearson Addison-Wesley

6.3 The if-else Statement

• An if-else statement has two parts:– An if clause– An else clause

• Just like a regular if statement, the if-else statement tests a Boolean expression

• If the expression is true– The block of statements following the if clause is executed– control of the program jumps to the statement that follows

the if-else statement• If the expression is false

– The block of statements following the else clause is executed

– Control of the program jumps to the statement that follows the if-else statement

1-30

Copyright © 2010 Pearson Addison-Wesley

6.3 The if-else Statement

• The action of an if-else statement is described in Figure 6-8

1-31

Figure 6-8 Conditional execution in an if-else statement

Copyright © 2010 Pearson Addison-Wesley

6.3 The if-else Statement

• The if-else statement has two sets of conditionally executed statements– One set is executed Only

• under the condition that the Boolean expression is true

– The other set is executed Only • under the condition that the Boolean expression is false

• Under no circumstances will both sets of conditionally executed statements be executed

1-32

Copyright © 2010 Pearson Addison-Wesley

6.3 The if-else Statement

• Remember that always enclosing conditionally executed statements in a set of curly braces is a good style of programming because it cuts down on errors

• If there is more than one conditionally executed statement following either – The if clause – Or the else clause

• Those statements must be enclosed in curly braces

1-33

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement

1-34

Concept:

To test more than one condition, a decision structure can be nested inside another decision structure.

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement

• Figure 6-10 shows a flowchart that combines a decision structure with two sequence structures

1-35Figure 6-10 Combining sequence

structures with a decision structure

• The flowchart starts with a sequence structure– The first step is Go to the window– The next step is Read thermometer

• A decision structure appears next, testing the condition Cold outside– If this is true

• The action Wear a coat is performed

– If this is false• The action is skipped

• Another sequence structure appears next– The step Open the door is performed– Followed by Go outside

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement

• Quite often, structures must be nested inside other structures

• Figure 6-11, it shows a decision structure with a sequence structure nested inside

• The decision structure tests the condition Cold outside– If the condition is true

• The steps in the sequence structure are executed

– If the condition is false• The steps in the sequence

structure are skipped

1-36

Figure 6-11 A sequence structure nested inside a decision

structure

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement

• You can also nest decision structures inside of other decision structures

• This is commonly done in programs that need to test more than one condition

1-37

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement• For example, suppose you want to determine whether the pixel

located at a specific location has a reddish tint– The following conditions must be determined:

• The pixel’s red component is at least 200• The pixel’s green component is less than 100• The pixel’s blue component is less than 100

• You can get the value of each color component by passing the pixel’s DWORD color value as an argument to the following functions:– The dbRGBR function

• Returns the integer value of the pixel’s red color component– The dbRGBG function

• Returns the integer value of the pixel’s green color component– The dbRGBB function

• Returns the integer value of the pixel’s blue color component

1-38

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement• Assume the variables x and y hold a set of XY coordinates

• The following code shows how you can:

– Get the color of the pixel located at (x, y)

– Determine whether the color is of the reddish tint described earlier

1-39(continued on next slide)

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement

• Proper indentation and alignment make it easier to see which if and else clauses belong together, as shown in Figure 6-15

1-40

Programming Style and Nested Decision Structures

Figure 6-15 Alignment of if and else clauses

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement

• The logic of nested decision structures can easily become complex

• C++ provides a special version of the decision structure known as the if-else-if statement, which makes this type of logic simpler to write

• Here is the general format of the if-else-if statement:

1-41

The if-else-if Statement

Copyright © 2010 Pearson Addison-Wesley

6.4 Nested Decision Structures and the if-else-if Statement

• When the else-if-else statement executes

– If (guess==number) is tested

– If it is true

• The block of statements that immediately follows is executed, and the rest of the structure is skipped

– If it is false

• The program jumps to the very next else if clause and tests else if (guess< myNumber)

– If it is true

• The block of statements that immediately follows is executed, and the rest of the structure is skipped

– This process continues until a condition is found to be true, or no more else if clauses are left

• If none of the conditions is true

– The block of statements following the else clause is executed

1-42

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

1-43

Concept:

A repetition structure causes a statement or set of statements to execute repeatedly.

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop• Programmers commonly have to write code that performs the same task over

and over

• For example, suppose you want to write a program that fills the screen with randomly placed dots to create the background for a space-themed game

• Although it would not be a good design, one approach would be to write the code to draw a single dot, and then repeat that code for the remaining dots

• For example, look at the following:

1-44

• There are several disadvantages to this approach, including the following:

– The duplicated code makes the program large

– Writing a long sequence of statements can be time consuming

– Any correction or change has to be done many times

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

1-45

• A better way to perform an operation repeatedly is to write code for the operation once, and then place that code in a structure that makes the computer repeat it as many times as necessary

• This can be done with a repetition structure, which is more commonly known as a loop

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• We will look at two broad categories of loops:

• Condition-Controlled

– Uses a true/false condition to control the number of times it repeats

– In C++, you use the

• while• do-while

– statements to write condition controlled loops

• Count-Controlled

– Repeats a specific number of times

– In C++, you use the• for

– statement to write count-controlled loops

1-46

Condition-Controlled and Count-Controlled Loops

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• The while loop gets its name from the way it works:

– While a Boolean expression is true, do some task

• The loop has two parts:

– A Boolean expression that is tested for a true or false value

– A statement or set of statements that is repeated as long as the Boolean expression is true

1-47

The while Loop

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

1-48

• Here is the general format of the while loop:

The while Loop

• We will refer to the first line as the while clause• The while clause begins with the word while, followed by a

Boolean expression that is enclosed in parentheses• Beginning on the next line is a block of statements that are

enclosed in curly braces• This block of statements is known as the body of the loop

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• When the while loop executes:– The Boolean expression is tested

• If the Boolean expression is true– The statements that appear in the body of the loop are

executed, and then the loop starts over

• If the Boolean expression is false– The loop ends and the program resumes execution at the

statement immediately following the loop

1-49

The while Loop

• We say that the statements in the body of the loop are conditionally executed because they are executed only under the condition that the Boolean expression is true

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

1-50

• Remember that always enclosing conditionally executed statements in a set of curly braces is a good style of programming because it cuts down on errors

• If there is more than one statement in the body of a loop, those statements must be enclosed in curly braces

The while Loop

• You should also notice that the statements in the body of the loop are indented

• This indentation makes the code easier to read and debug, and visually sets them apart from the surrounding code

• Most programmers use this style of indentation when writing loops

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• The while loop is a pretest loop, which means it tests its Boolean expression before performing an iteration

• This is an important characteristic of the while loop:– It will never execute if its condition is false to

start with

1-51

The while Loop Is a Pretest Loop

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• In all but rare cases, loops must contain within themselves a way to terminate

• Something inside the loop must eventually make the loop’s Boolean expression false

• If a loop does not have a way of stopping it is called an infinite loop

• An infinite loop continues to repeat until the program is interrupted

1-52

Infinite Loops

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• Infinite loops usually occur when the programmer forgets to write code inside the loop that makes the test condition false

• For example, suppose we forgot to write the statement that subtracts 1 from numBricks, as shown here:

1-53

Infinite Loops

• numBricks will always contain the same value

• The loop has no way of stopping

• The numBricks variable is an example of a loop control variable• Its value is tested by the loop, and controls whether the loop will

iterate

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• The do-while loop is a posttest loop.

• It performs an iteration before testing its Boolean expression

• The do-while loop performs at least one iteration, even if its Boolean expression is false to begin with

1-54

The do-while Loop: A Posttest Loop

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• The logic of a do-while loop is shown in Figure 6-21

1-55

The do-while Loop: A Posttest Loop

Figure 6-21 The logic of a do-while loop• In the flowchart, one or more statements are executed

– And then a Boolean expression is tested

– If the Boolean expression is true

• The programs execution flows to just above the first statement in the body of the loop

• The process repeats

– If the Boolean expression is false

• The program exits the loop

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• In code, the do-while loop looks something like an inverted while loop• Here is the general format of the do-while loop:

1-56

The do-while Loop: A Posttest Loop

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• The do-while loop always performs at least one iteration, even if the expression is false to begin with

• This differs from the behavior of a while loop• For example, in the following while loop the statement

that calls dbPrint will not execute at all:

1-57

The do-while Loop: A Posttest Loop

Copyright © 2010 Pearson Addison-Wesley

6.5 Repetition Structures: The while Loop and the do-while Loop

• The statement that calls dbPrint in the following do-while loop will execute one time

• The do-while loop does not test the expression number < 0 until the end of the iteration

1-58

The do-while Loop: A Posttest Loop

Copyright © 2010 Pearson Addison-Wesley

6.6 The Increment and Decrement Operators

1-59

Concept:

To increment a variable means to increase its value, and to decrement a variable means to decrease its value. C++ provides special operators to increment and decrement variables.

Copyright © 2010 Pearson Addison-Wesley

6.6 The Increment and Decrement Operators

1-60

• To increment a variable means to increase its value• Both the following statements increment the variable num by one:

• To decrement a variable means to decrease its value• Both the following statements decrement the variable num by one:

Copyright © 2010 Pearson Addison-Wesley

6.6 The Increment and Decrement Operators

• Incrementing and decrementing is so commonly done in programs that C++ provides a set of simple unary operators designed just for incrementing and decrementing variables

1-61

– The increment operator is ++– The following statement uses the ++ operator to add 1 to num:

– The decrement operator is --– The following statement uses the -- operator to subtract 1 from num:

Copyright © 2010 Pearson Addison-Wesley

6.6 The Increment and Decrement Operators

• Writing the ++ and -- operators after their operands is called postfix mode• The ++ and -- operators can also be written before their operands, which is

called prefix mode– Here are examples of prefix mode:

1-62

• When you write a simple statement to increment or decrement a variable– It does not matter if you use prefix or postfix mode

• If you write statements that mix these operators with other operators or operations– There is a difference in the way the two modes work– Such complex code can be difficult to understand and debug

• We will use the increment and decrement operators only in ways that are easy to understand

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

1-63

Concept:

A count-controlled loop iterates a specific number of times. In C++, you use the for statement to write a count-controlled loop.

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

1-64

• The way that a count-controlled loop works is simple:– The loop keeps a count of the number of times

it iterates– When the count reaches a specified amount,

the loop stops

• A count-controlled loop uses a variable known as a counter variable, or simply counter, to store the number of iterations that it has performed

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• Using the counter variable, a count-controlled loop performs the following three actions:

• (1) Initialization:

– Before the loop begins, the counter variable is initialized to a starting value

• (2) Test:

– The loop tests the counter variable by comparing it to a maximum value

• If it has not reached the maximum value

– The loop iterates

• If it has reached the maximum value

– The program exits the loop

• (3) Increment:

– During each iteration, the loop increments the counter variable

1-65

Figure 6-22 Logic of a count-controlled loop

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• Count-controlled loops are so common that C++ provides a type of loop just for them

– It is known as the for loop

• The for loop is specifically designed to

– Initialize

– Test

– And increment the counter variable

• Here is the general format of the for loop:

1-66

• The statements that appear inside the curly braces are the body of the loop• These are the statements that are executed each time the loop iterates

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• The first line of the for loop is the loop header– After the key word for– There are three expressions inside the parentheses,

separated by semicolons– Notice that there is not a semicolon after the third expression

1-67

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• The first expression:– is the initialization expression– is normally used to initialize the counter variable to its starting value– is the first action done by the loop– is only done once

1-68

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• The second expression:– is the test expression– is the Boolean expression that controls the execution of the loop– Will repeat the body of the for loop as long as this expression is

true– is evaluated before each iteration

1-69

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• The third expression:– Is the increment expression– Executes at the end of each iteration– Typically, is the statement that increments the loop’s counter variable

1-70

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• Here is an example of a simple for loop that prints “Hello” five times:

1-71

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• Not only may the counter variable be initialized in the initialization expression, but it also may be declared there

• The following code shows an example:

1-72

Declaring the Counter Variable in the Initialization Expression

• If the variable is used only in the loop, it makes sense to declare it in the loop header

• This makes the variable’s purpose clearer

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• When a variable is declared in the initialization expression of a for loop– The variable is limited in scope– You cannot access the variable in statements outside the loop

• For example, the following code would cause a compile error because the last statement cannot access the count variable

1-73

Declaring the Counter Variable in the Initialization Expression

• Error! count cannot be accessed outside the loop

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

1-74

Using the Counter Variable in the Body of the Loop

• The counter variable is named count

• count is initialized with the value 1

• The loop iterates five times

• count is incremented after each iteration

• count is used in the calculation of the circle’s radius

• The first circle’s radius will be 50

• The second circle’s radius will be 100

• The third circle’s radius will be 150

• and so forth

Copyright © 2010 Pearson Addison-Wesley

6.7 Repetition Structures: The for Loop

• The amount by which the counter variable is incremented in a for loop is typically 1

• You can write virtually any expression you wish as the increment expression

• For example, the following loop increments count by 10

1-75

Incrementing by Values Other than 1

• Notice the increment expression is count += 10– At the end of each iteration 10 will added to count– During the first iteration

• count will be set to 1

– During the second iteration • count will be set to 11

– During the third iteration • count will be set to 21

– And so forth

Copyright © 2010 Pearson Addison-Wesley

6.8 Using the for Loop to Process Pixels in an Image

1-76

Concept:

You can use the for loop to get the color of each pixel in an image and perform some operation using that color value.

Copyright © 2010 Pearson Addison-Wesley

6.8 Using the for Loop to Process Pixels in an Image

1-77

• Pixels are arranged in rows and columns– Rows correspond to the Y coordinates– Columns correspond to the X coordinates

Figure 6-25 Think of pixels as

arranged in rows and columns

Copyright © 2010 Pearson Addison-Wesley

6.8 Using the for Loop to Process Pixels in an Image

• To step through each of the pixels, we need two loops, one nested inside the other

• The outer loop will step through the rows• The inner loop will step through the columns

1-78

Copyright © 2010 Pearson Addison-Wesley

6.9 Logical Operators

1-79

Concept:

The logical AND operator (&&) and the logical OR operator (||) allow you to connect multiple Boolean expressions to create a compound expression. The logical NOT operator (!) reverses the truth of a Boolean expression.

Copyright © 2010 Pearson Addison-Wesley

6.9 Logical Operators

• The C++ language provides a set of operators known as logical operators, which you can use to create complex Boolean expressions

• Table 6-3 describes these operators

1-80

Copyright © 2010 Pearson Addison-Wesley

6.9 Logical Operators

• The && operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true only when both subexpressions are true

1-81

The && Operator

Copyright © 2010 Pearson Addison-Wesley

6.9 Logical Operators

• The || operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true when either of the subexpressions is true

1-82

The || Operator

Copyright © 2010 Pearson Addison-Wesley

6.9 Logical Operators

• Both the && and || operators perform short-circuit evaluation

• The && will short-circuit if the expression on the left is false, and the right side will not be tested

• The || operator will short-circuit if the expression on the left is true, and the right side will not be tested

1-83

Short-Circuit Evaluation

Copyright © 2010 Pearson Addison-Wesley

6.9 Logical Operators

• The ! operator is a unary operator that takes a Boolean expression as its operand and reverses its logical value

1-84

The ! Operator

Copyright © 2010 Pearson Addison-Wesley

6.9 Logical Operators

• The ! operator has a higher precedence that the relational operators

• The && and || operators have a lower precedence that the relational operators

1-85

Precedence of the Logical Operators

• Many programmers use parentheses to enclose expressions that are to the left and right of a logical operator

Copyright © 2010 Pearson Addison-Wesley

6.10 The switch Statement

1-86

Concept:

The switch statement lets the value of a variable or an expression determine which path of execution the program will take.

Copyright © 2010 Pearson Addison-Wesley

6.10 The switch Statement

• The switch statement is a multiple alternative decision structure• It tests the value of an integer variable or an expression and then

uses that value to determine which statement or set of statements to execute

1-87

Figure 6-28 A switch statement

Copyright © 2010 Pearson Addison-Wesley

6.10 The switch Statement

1-88

• Here is the general format of the switch statement:

Copyright © 2010 Pearson Addison-Wesley

6.10 The switch Statement

• For example, the following code performs the same operation as the flowchart in Figure 6-28:

1-89

Copyright © 2010 Pearson Addison-Wesley

6.11 Numeric Truth, Flags, and bool Variables

1-90

Concept:

In addition to the values of relational expressions, you can use numeric values to represent true or false conditions. You can store the values true and false in bool variables, which are commonly used as flags.

Copyright © 2010 Pearson Addison-Wesley

6.11 Numeric Truth, Flags, and bool Variables

• C++ considers the numeric value 0 as false • Any numeric value other than 0 as true• Functions that return a value of 0 are considered false• Functions that return a value of 1 are considered true• For example:

1-91

Copyright © 2010 Pearson Addison-Wesley

6.11 Numeric Truth, Flags, and bool Variables

• The C++ language provides a special data type named bool that you can use to create variables that hold true or false values

• Here is an example of the declaration of a bool variable:

1-92

bool Variables

• We can assign the special values true or false to the variable, as shown here:

Copyright © 2010 Pearson Addison-Wesley

6.11 Numeric Truth, Flags, and bool Variables

• Variables of the bool data type are commonly used as flags• A flag is a variable that signals when some condition exists in the

program– When a flag is set to false it indicates the condition does not exist– When a flag is set to true it indicates the condition does exist

• For example:

1-93

bool Variables

Addison Wesley is an imprint of

© 2010 Pearson Addison-Wesley. All rights reserved.

Chapter 6Control Structures

QUESTIONS

?