Presentation is loading. Please wait.

# Chapter 6 Control Structures

## Presentation on theme: "Chapter 6 Control Structures"— Presentation transcript:

Chapter 6 Control Structures
Starting Out with Games & Graphics in C++ Tony Gaddis

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.

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

6.1 Introduction For an example of a sequence structure, look at the following DarkGDK function: The statements inside the function are a sequence structure They execute in the order they are written from top to bottom

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 Figure 6-1 Flowchart for a sequence structure

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

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

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.

6.2 Writing a Decision Structure with the if statement
Figure 6-2 A simple decision, structure, also known as a single alternative decision structure 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

6.2 Writing a Decision Structure with the if statement
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

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

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

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

6.2 Writing a Decision Structure with the if statement
Boolean Expressions and Relational Operators 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++

6.2 Writing a Decision Structure with the if statement
Boolean Expressions and Relational Operators 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

6.2 Writing a Decision Structure with the if statement
Boolean Expressions and Relational Operators The >= and <= Operators 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:

6.2 Writing a Decision Structure with the if statement
Boolean Expressions and Relational Operators The == Operator 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

6.2 Writing a Decision Structure with the if statement
Boolean Expressions and Relational Operators The != Operator 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

6.2 Writing a Decision Structure with the if statement
Putting It All Together Let’s look at the following example of the if statement: This statement uses the > operator to determine whether sales is greater than 50,000 If the expression sales > is true The variable bonus is assigned 500 If the expression is false The assignment is skipped Figure 6-4 Example decision structure

6.2 Writing a Decision Structure with the if statement
Putting It All Together Figure 6-5 Example decision structure The following example conditionally executes three statements

6.2 Writing a Decision Structure with the if statement
Putting It All Together 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

6.2 Writing a Decision Structure with the if statement
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

6.2 Writing a Decision Structure with the if statement
Testing Colors 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

6.2 Writing a Decision Structure with the if statement
Testing Colors 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: 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

6.2 Writing a Decision Structure with the if statement
Testing Colors 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

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.

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

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 Figure 6-7 A dual alternative decision structure

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:

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

6.3 The if-else Statement The action of an if-else statement is described in Figure 6-8 Figure 6-8 Conditional execution in an if-else statement

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

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

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.

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 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 Figure 6-10 Combining sequence structures with a decision structure

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 Figure 6-11 A sequence structure nested inside a decision structure

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

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

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 (continued on next slide)

6.4 Nested Decision Structures and the if-else-if Statement
Programming Style and Nested Decision Structures Proper indentation and alignment make it easier to see which if and else clauses belong together, as shown in Figure 6-15 Figure 6-15 Alignment of if and else clauses

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:

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) 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

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.

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: 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

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 necessary This can be done with a repetition structure, which is more commonly known as a loop

6.5 Repetition Structures: The while Loop and the do-while Loop
Condition-Controlled and Count-Controlled Loops 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 for statement to write count-controlled loops

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

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

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

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 errors If there is more than one statement in the body of a loop, those statements must be enclosed in curly braces 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

6.5 Repetition Structures: The while Loop and the do-while Loop
The while Loop Is a Pretest 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

6.5 Repetition Structures: The while Loop and the do-while Loop
Infinite Loops 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

6.5 Repetition Structures: The while Loop and the do-while Loop
Infinite Loops 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: 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

6.5 Repetition Structures: The while Loop and the do-while Loop
The do-while Loop: A Posttest 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

6.5 Repetition Structures: The while Loop and the do-while Loop
The do-while Loop: A Posttest Loop The logic of a do-while loop is shown in Figure 6-21 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 Figure 6-21 The logic of a do-while loop

6.5 Repetition Structures: The while Loop and the do-while Loop
The do-while Loop: A Posttest Loop In code, the do-while loop looks something like an inverted while loop Here is the general format of the do-while loop:

6.5 Repetition Structures: The while Loop and the do-while Loop
The do-while Loop: A Posttest 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:

6.5 Repetition Structures: The while Loop and the do-while Loop
The do-while Loop: A Posttest 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

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.

6.6 The Increment and Decrement Operators
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:

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 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:

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: 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

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.

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

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 Figure 6-22 Logic of a count-controlled loop

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: 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

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

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

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

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

6.7 Repetition Structures: The for Loop
Here is an example of a simple for loop that prints “Hello” five times:

6.7 Repetition Structures: The for Loop
Declaring the Counter Variable in the Initialization Expression 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: 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

6.7 Repetition Structures: The for Loop
Declaring the Counter Variable in the Initialization Expression 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 Error! count cannot be accessed outside the loop

6.7 Repetition Structures: The for Loop
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

6.7 Repetition Structures: The for Loop
Incrementing by Values Other than 1 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 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

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.

6.8 Using the for Loop to Process Pixels in an Image
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

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

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.

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

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

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

6.9 Logical Operators Short-Circuit Evaluation
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

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

6.9 Logical Operators Precedence of the Logical Operators
The ! operator has a higher precedence that the relational operators The && and || operators have a lower precedence that the relational operators Many programmers use parentheses to enclose expressions that are to the left and right of a logical operator

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.

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 Figure A switch statement

6.10 The switch Statement Here is the general format of the switch statement:

6.10 The switch Statement For example, the following code performs the same operation as the flowchart in Figure 6-28:

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.

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:

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: We can assign the special values true or false to the variable, as shown here:

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:

Chapter 6 Control Structures
QUESTIONS ?

Download ppt "Chapter 6 Control Structures"

Similar presentations

Ads by Google