Presentation on theme: "Chapter 6 Control Structures"— Presentation transcript:
1 Chapter 6 Control Structures Starting Out withGames & Graphics in C++Tony Gaddis
2 6.1 Introduction Concept: Control structures affect the order in which statements execute. There are three main types of control structures: sequence, decision, and repetition.
3 6.1 IntroductionA control structure determines the order in which a set of statements executeIn 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 structureThe decision structureThe repetition structureThe simplest of these structures is the sequence structure, which is a set of statements that execute in the order they appear
4 6.1 IntroductionFor an example of a sequence structure, look at the following DarkGDK function:The statements inside the function are a sequence structureThey execute in the order they are written from top to bottom
5 6.1 IntroductionFlowcharts, planning tools that programmers use to design a program’s logicTerminals, elliptical symbols at the top and bottom of the flowchart that mark the algorithm’s start and end pointsThe symbols that appear between the terminals are the steps taken in the algorithmThe steps are connected by arrows that represent the flow of executionThe flowchart in Figure 6-1 depicts a sequence structure because the steps are taken one after another, from the beginning to the endFigure 6-1 Flowchart for a sequence structure
6 6.1 IntroductionSome problems simply cannot be solved by performing a set of ordered steps, one after anotherIn some programs, a set of statements must be executed only under certain circumstancesIf those circumstances do not exist, the statements should be skippedConsider a company payroll program that determines whether an employee has worked overtimeIf the employee has worked more than 40 hours, he or she gets paid a higher wage for the hours over 40Otherwise, the overtime calculation should be skippedSolving this kind of problem requires a decision structure
7 6.1 IntroductionSuppose the same payroll program calculates pay for all employeesThis means that it has to perform the same steps for each employeeSolving 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
8 6.2 Writing a Decision Structure with the if statement 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.
9 6.2 Writing a Decision Structure with the if statement Figure 6-2 A simple decision, structure, also known as a single alternative decision structureIn a decision structure’s simplest formA specific action is performed only if a certain condition existsIf the condition does not exist, the action is not performedA single alternative, as shown in Figure 6-2, provides only one alternative path of executionIf the condition in the diamond symbol is trueWe take the alternate pathOtherwise, we exit the structure
10 6.2 Writing a Decision Structure with the if statement The diamond symbol indicates some condition that must be testedWe are determining whether the condition Cold outside is true or falseIf this condition is true, the action is performedIf the condition is false, the action is skippedThe action is conditionally executed because it is performed only when a certain condition is true
11 6.2 Writing a Decision Structure with the if statement Here is the general format of the if statement:The statement begins with the word ifFollowed by an expression that is enclosed in a set of parenthesesBeginning on the next line is a set of statements enclosed in curly braces
12 6.2 Writing a Decision Structure with the if statement The expression that appears inside the parentheses is a Boolean expression , which is an expression that can be evaluated as either true or falseWhen the if statement executes, the Boolean expression is testedIf it is true, the statements that appear inside the curly braces are executedIf it is false the statements inside the curly braces are skipped
13 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:This is a good style of writing if statements because it minimizes errors
14 6.2 Writing a Decision Structure with the if statement Boolean Expressions and Relational OperatorsThe value of a Boolean expression can be either true or falseTypically, the Boolean expression that is tested by an if statement is formed with a relational operatorA relational operator determines whether a specific relationship exists between two valuesTable 6-1 lists the relational operators that are available in C++
15 6.2 Writing a Decision Structure with the if statement Boolean Expressions and Relational OperatorsTable 6-2 shows examples of several Boolean expressions that compare the variables x and yThese expressions determine whether the value is true or false
16 6.2 Writing a Decision Structure with the if statement Boolean Expressions and Relational OperatorsThe >= and <= OperatorsTwo of the operators, >= and <=, test for more than one relationshipThe >= operatorDetermines whether the operand on its left is greater than or equal to the operand on its rightThe <= operatorDetermines whether the on its left is less than or equal to the operand on its rightFor example, assume the variable a is assigned the value 4All of the following expressions are true:
17 6.2 Writing a Decision Structure with the if statement Boolean Expressions and Relational OperatorsThe == OperatorThe == operator determines whether the operand on its left is equal to the operand on its rightIf the values of both operands are the same, the expression is trueAssuming that a is 4The expression a == 4 is trueThe expression a == 2 is false
18 6.2 Writing a Decision Structure with the if statement Boolean Expressions and Relational OperatorsThe != OperatorThe != operator is the not-equal-to operatorIt determines whether the operand on the left is not equal to the operand on the right, which is the opposite of the == operatorAssuming a is 4, b is 6, and c is 4Both a != b and b != c are trueThis is because a is not equal to b and b is not equal to cHowever, a != c is falseThis is because a is equal to c
19 6.2 Writing a Decision Structure with the if statement Putting It All TogetherLet’s look at the following example of the if statement:This statement uses the > operator to determine whether sales is greater than 50,000If the expression sales > is trueThe variable bonus is assigned 500If the expression is falseThe assignment is skippedFigure 6-4 Example decision structure
20 6.2 Writing a Decision Structure with the if statement Putting It All TogetherFigure 6-5 Example decision structureThe following example conditionally executes three statements
21 6.2 Writing a Decision Structure with the if statement Putting It All TogetherNotice that in both the previous if statement examples, the conditionally executed statements were indentedThis indentation is not required, but it makes code easier to read and debugMost programmers use this style of indentation when writing if statements
22 6.2 Writing a Decision Structure with the if statement Putting It All TogetherLet’s look at a complete program that uses an if statementThe program calculates the average of three test scoresIf the average is greater than 95, it should display the image stored in a file named Congrats.bmp
23 6.2 Writing a Decision Structure with the if statement Testing ColorsYou can use the relational operators to compare RGB valuesFor example, suppose you have two DWORD variables named color1 and color2The following if statement determines whether they hold the same value
24 6.2 Writing a Decision Structure with the if statement Testing ColorsIf 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 valueYou pass two arguments to the dbPoint functionAn X coordinateA Y coordinateThe dbPoint function returns a DWORD value containing the color of that pointThe following code shows an example:The first statement declares a DWORD variable named pixelColorThe 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
25 6.2 Writing a Decision Structure with the if statement Testing ColorsThe following code shows another exampleThe code gets the color of the pixel located at (10, 10)If that pixel’s color is blue, it is changed to red
26 6.3 The if-else Statement 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.
27 6.3 The if-else StatementThe dual alternative decision structure has two possible paths of executionOne path is taken if the Boolean expression is trueThe other path is taken if the Boolean expression is false
28 6.3 The if-else StatementFigure 6-7 shows an example flowchart for a dual alternative decision structureThe decision structure in the flowchart tests the expression temperature < 40If the expression is trueThe message “A little cold, isn’t it?” is displayedIf the expression is falseThe message “Nice weather we’re having.” is displayedFigure 6-7 A dual alternative decision structure
29 6.3 The if-else StatementIn code we write a dual alternative decision structure as an if-else statementHere is the general format of the if-else statement:
30 6.3 The if-else Statement An if-else statement has two parts: An if clauseAn else clauseJust like a regular if statement, the if-else statement tests a Boolean expressionIf the expression is trueThe block of statements following the if clause is executedcontrol of the program jumps to the statement that follows the if-else statementIf the expression is falseThe block of statements following the else clause is executedControl of the program jumps to the statement that follows the if-else statement
31 6.3 The if-else StatementThe action of an if-else statement is described in Figure 6-8Figure 6-8 Conditional execution in an if-else statement
32 6.3 The if-else StatementThe if-else statement has two sets of conditionally executed statementsOne set is executed Onlyunder the condition that the Boolean expression is trueThe other set is executed Onlyunder the condition that the Boolean expression is falseUnder no circumstances will both sets of conditionally executed statements be executed
33 6.3 The if-else StatementRemember that always enclosing conditionally executed statements in a set of curly braces is a good style of programming because it cuts down on errorsIf there is more than one conditionally executed statement following eitherThe if clauseOr the else clauseThose statements must be enclosed in curly braces
34 6.4 Nested Decision Structures and the if-else-if Statement Concept:To test more than one condition, a decision structure can be nested inside another decision structure.
35 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 structuresThe flowchart starts with a sequence structureThe first step is Go to the windowThe next step is Read thermometerA decision structure appears next, testing the condition Cold outsideIf this is trueThe action Wear a coat is performedIf this is falseThe action is skippedAnother sequence structure appears nextThe step Open the door is performedFollowed by Go outsideFigure 6-10 Combining sequence structures with a decision structure
36 6.4 Nested Decision Structures and the if-else-if Statement Quite often, structures must be nested inside other structuresFigure 6-11, it shows a decision structure with a sequence structure nested insideThe decision structure tests the condition Cold outsideIf the condition is trueThe steps in the sequence structure are executedIf the condition is falseThe steps in the sequence structure are skippedFigure 6-11 A sequence structure nested inside a decision structure
37 6.4 Nested Decision Structures and the if-else-if Statement You can also nest decision structures inside of other decision structuresThis is commonly done in programs that need to test more than one condition
38 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 tintThe following conditions must be determined:The pixel’s red component is at least 200The pixel’s green component is less than 100The pixel’s blue component is less than 100You 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 functionReturns the integer value of the pixel’s red color componentThe dbRGBG functionReturns the integer value of the pixel’s green color componentThe dbRGBB functionReturns the integer value of the pixel’s blue color component
39 6.4 Nested Decision Structures and the if-else-if Statement Assume the variables x and y hold a set of XY coordinatesThe 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(continued on next slide)
40 6.4 Nested Decision Structures and the if-else-if Statement Programming Style and Nested Decision StructuresProper indentation and alignment make it easier to see which if and else clauses belong together, as shown in Figure 6-15Figure 6-15 Alignment of if and else clauses
41 6.4 Nested Decision Structures and the if-else-if Statement The logic of nested decision structures can easily become complexC++ provides a special version of the decision structure known as the if-else-if statement, which makes this type of logic simpler to writeHere is the general format of the if-else-if statement:
42 6.4 Nested Decision Structures and the if-else-if Statement When the else-if-else statement executesIf (guess==number) is testedIf it is trueThe block of statements that immediately follows is executed, and the rest of the structure is skippedIf it is falseThe program jumps to the very next else if clause and tests else if (guess< myNumber)This process continues until a condition is found to be true, or no more else if clauses are leftIf none of the conditions is trueThe block of statements following the else clause is executed
43 6.5 Repetition Structures: The while Loop and the do-while Loop Concept:A repetition structure causes a statement or set of statements to execute repeatedly.
44 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 overFor example, suppose you want to write a program that fills the screen with randomly placed dots to create the background for a space-themed gameAlthough 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 dotsFor example, look at the following:There are several disadvantages to this approach, including the following:The duplicated code makes the program largeWriting a long sequence of statements can be time consumingAny correction or change has to be done many times
45 6.5 Repetition Structures: The while Loop and the do-while Loop 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 necessaryThis can be done with a repetition structure, which is more commonly known as a loop
46 6.5 Repetition Structures: The while Loop and the do-while Loop Condition-Controlled and Count-Controlled LoopsWe will look at two broad categories of loops:Condition-ControlledUses a true/false condition to control the number of times it repeatsIn C++, you use thewhiledo-whilestatements to write condition controlled loopsCount-ControlledRepeats a specific number of timesforstatement to write count-controlled loops
47 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 taskThe loop has two parts:A Boolean expression that is tested for a true or false valueA statement or set of statements that is repeated as long as the Boolean expression is true
48 6.5 Repetition Structures: The while Loop and the do-while Loop Here is the general format of the while loop:We will refer to the first line as the while clauseThe while clause begins with the word while, followed by a Boolean expression that is enclosed in parenthesesBeginning on the next line is a block of statements that are enclosed in curly bracesThis block of statements is known as the body of the loop
49 6.5 Repetition Structures: The while Loop and the do-while Loop When the while loop executes:The Boolean expression is testedIf the Boolean expression is trueThe statements that appear in the body of the loop are executed, and then the loop starts overIf the Boolean expression is falseThe loop ends and the program resumes execution at the statement immediately following the loopWe 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
50 6.5 Repetition Structures: The while Loop and the do-while Loop Remember that always enclosing conditionally executed statements in a set of curly braces is a good style of programming because it cuts down on errorsIf there is more than one statement in the body of a loop, those statements must be enclosed in curly bracesYou should also notice that the statements in the body of the loop are indentedThis indentation makes the code easier to read and debug, and visually sets them apart from the surrounding codeMost programmers use this style of indentation when writing loops
51 6.5 Repetition Structures: The while Loop and the do-while Loop The while Loop Is a Pretest LoopThe while loop is a pretest loop, which means it tests its Boolean expression before performing an iterationThis is an important characteristic of the while loop:It will never execute if its condition is false to start with
52 6.5 Repetition Structures: The while Loop and the do-while Loop Infinite LoopsIn all but rare cases, loops must contain within themselves a way to terminateSomething inside the loop must eventually make the loop’s Boolean expression falseIf a loop does not have a way of stopping it is called an infinite loopAn infinite loop continues to repeat until the program is interrupted
53 6.5 Repetition Structures: The while Loop and the do-while Loop Infinite LoopsInfinite loops usually occur when the programmer forgets to write code inside the loop that makes the test condition falseFor example, suppose we forgot to write the statement that subtracts 1 from numBricks, as shown here:numBricks will always contain the same valueThe loop has no way of stoppingThe numBricks variable is an example of a loop control variableIts value is tested by the loop, and controls whether the loop will iterate
54 6.5 Repetition Structures: The while Loop and the do-while Loop The do-while Loop: A Posttest LoopThe do-while loop is a posttest loop.It performs an iteration before testing its Boolean expressionThe do-while loop performs at least one iteration, even if its Boolean expression is false to begin with
55 6.5 Repetition Structures: The while Loop and the do-while Loop The do-while Loop: A Posttest LoopThe logic of a do-while loop is shown in Figure 6-21In the flowchart, one or more statements are executedAnd then a Boolean expression is testedIf the Boolean expression is trueThe programs execution flows to just above the first statement in the body of the loopThe process repeatsIf the Boolean expression is falseThe program exits the loopFigure 6-21 The logic of a do-while loop
56 6.5 Repetition Structures: The while Loop and the do-while Loop The do-while Loop: A Posttest LoopIn code, the do-while loop looks something like an inverted while loopHere is the general format of the do-while loop:
57 6.5 Repetition Structures: The while Loop and the do-while Loop The do-while Loop: A Posttest LoopThe do-while loop always performs at least one iteration, even if the expression is false to begin withThis differs from the behavior of a while loopFor example, in the following while loop the statement that calls dbPrint will not execute at all:
58 6.5 Repetition Structures: The while Loop and the do-while Loop The do-while Loop: A Posttest LoopThe statement that calls dbPrint in the following do-while loop will execute one timeThe do-while loop does not test the expression number < 0 until the end of the iteration
59 6.6 The Increment and Decrement Operators 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.
60 6.6 The Increment and Decrement Operators To increment a variable means to increase its valueBoth the following statements increment the variable num by one:To decrement a variable means to decrease its valueBoth the following statements decrement the variable num by one:
61 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 variablesThe 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:
62 6.6 The Increment and Decrement Operators Writing the ++ and -- operators after their operands is called postfix modeThe ++ and -- operators can also be written before their operands, which is called prefix modeHere are examples of prefix mode:When you write a simple statement to increment or decrement a variableIt does not matter if you use prefix or postfix modeIf you write statements that mix these operators with other operators or operationsThere is a difference in the way the two modes workSuch complex code can be difficult to understand and debugWe will use the increment and decrement operators only in ways that are easy to understand
63 6.7 Repetition Structures: The for Loop Concept:A count-controlled loop iterates a specific number of times. In C++, you use the for statement to write a count-controlled loop.
64 6.7 Repetition Structures: The for Loop The way that a count-controlled loop works is simple:The loop keeps a count of the number of times it iteratesWhen the count reaches a specified amount, the loop stopsA count-controlled loop uses a variable known as a counter variable, or simply counter, to store the number of iterations that it has performed
65 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 valueIf it has not reached the maximum valueThe loop iteratesIf it has reached the maximum valueThe program exits the loop(3) Increment:During each iteration, the loop increments the counter variableFigure 6-22 Logic of a count-controlled loop
66 6.7 Repetition Structures: The for Loop Count-controlled loops are so common that C++ provides a type of loop just for themIt is known as the for loopThe for loop is specifically designed toInitializeTestAnd increment the counter variableHere is the general format of the for loop:The statements that appear inside the curly braces are the body of the loopThese are the statements that are executed each time the loop iterates
67 6.7 Repetition Structures: The for Loop The first line of the for loop is the loop headerAfter the key word forThere are three expressions inside the parentheses, separated by semicolonsNotice that there is not a semicolon after the third expression
68 6.7 Repetition Structures: The for Loop The first expression:is the initialization expressionis normally used to initialize the counter variable to its starting valueis the first action done by the loopis only done once
69 6.7 Repetition Structures: The for Loop The second expression:is the test expressionis the Boolean expression that controls the execution of the loopWill repeat the body of the for loop as long as this expression is trueis evaluated before each iteration
70 6.7 Repetition Structures: The for Loop The third expression:Is the increment expressionExecutes at the end of each iterationTypically, is the statement that increments the loop’s counter variable
71 6.7 Repetition Structures: The for Loop Here is an example of a simple for loop that prints “Hello” five times:
72 6.7 Repetition Structures: The for Loop Declaring the Counter Variable in the Initialization ExpressionNot only may the counter variable be initialized in the initialization expression, but it also may be declared thereThe following code shows an example:If the variable is used only in the loop, it makes sense to declare it in the loop headerThis makes the variable’s purpose clearer
73 6.7 Repetition Structures: The for Loop Declaring the Counter Variable in the Initialization ExpressionWhen a variable is declared in the initialization expression of a for loopThe variable is limited in scopeYou cannot access the variable in statements outside the loopFor example, the following code would cause a compile error because the last statement cannot access the count variableError! count cannot be accessed outside the loop
74 6.7 Repetition Structures: The for Loop Using the Counter Variable in the Body of the LoopThe counter variable is named countcount is initialized with the value 1The loop iterates five timescount is incremented after each iterationcount is used in the calculation of the circle’s radiusThe first circle’s radius will be 50The second circle’s radius will be 100The third circle’s radius will be 150and so forth
75 6.7 Repetition Structures: The for Loop Incrementing by Values Other than 1The amount by which the counter variable is incremented in a for loop is typically 1You can write virtually any expression you wish as the increment expressionFor example, the following loop increments count by 10Notice the increment expression is count += 10At the end of each iteration 10 will added to countDuring the first iterationcount will be set to 1During the second iterationcount will be set to 11During the third iterationcount will be set to 21And so forth
76 6.8 Using the for Loop to Process Pixels in an Image 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.
77 6.8 Using the for Loop to Process Pixels in an Image Pixels are arranged in rows and columnsRows correspond to the Y coordinatesColumns correspond to the X coordinatesFigure 6-25 Think of pixels as arranged in rows and columns
78 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 otherThe outer loop will step through the rowsThe inner loop will step through the columns
79 6.9 Logical Operators 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.
80 6.9 Logical OperatorsThe C++ language provides a set of operators known as logical operators, which you can use to create complex Boolean expressionsTable 6-3 describes these operators
81 6.9 Logical Operators The && Operator The && operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true only when both subexpressions are true
82 6.9 Logical Operators The || Operator The || operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true when either of the subexpressions is true
83 6.9 Logical Operators Short-Circuit Evaluation Both the && and || operators perform short-circuit evaluationThe && will short-circuit if the expression on the left is false, and the right side will not be testedThe || operator will short-circuit if the expression on the left is true, and the right side will not be tested
84 6.9 Logical Operators The ! Operator The ! operator is a unary operator that takes a Boolean expression as its operand and reverses its logical value
85 6.9 Logical Operators Precedence of the Logical Operators The ! operator has a higher precedence that the relational operatorsThe && and || operators have a lower precedence that the relational operatorsMany programmers use parentheses to enclose expressions that are to the left and right of a logical operator
86 6.10 The switch Statement Concept: The switch statement lets the value of a variable or an expression determine which path of execution the program will take.
87 6.10 The switch StatementThe switch statement is a multiple alternative decision structureIt tests the value of an integer variable or an expression and then uses that value to determine which statement or set of statements to executeFigure A switch statement
88 6.10 The switch StatementHere is the general format of the switch statement:
89 6.10 The switch StatementFor example, the following code performs the same operation as the flowchart in Figure 6-28:
90 6.11 Numeric Truth, Flags, and bool Variables 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.
91 6.11 Numeric Truth, Flags, and bool Variables C++ considers the numeric value 0 as falseAny numeric value other than 0 as trueFunctions that return a value of 0 are considered falseFunctions that return a value of 1 are considered trueFor example:
92 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 valuesHere is an example of the declaration of a bool variable:We can assign the special values true or false to the variable, as shown here:
93 6.11 Numeric Truth, Flags, and bool Variables Variables of the bool data type are commonly used as flagsA flag is a variable that signals when some condition exists in the programWhen a flag is set to false it indicates the condition does not existWhen a flag is set to true it indicates the condition does existFor example:
Your consent to our cookies if you continue to use this website.