Study Guide - Chapter 6 Control Structures

ITP 134 C++ Programming Notes

Instructions: Use these notes to give you the important points of this chapter. See the book for lots of great programming examples. Important concepts, keywords, statements and functions are shown in emphasized font.

Chapter 6 Control Structures

ITP 134 – Chapter 6Mrs. EatonPage 1

Study Guide - Chapter 6 Control Structures

6.1 Introduction

CONCEPT: Control structures affect the order in which statements execute. There are 3 main types of control structures, sequence, decision, and repetition. (pg 213)

  1. Sequence – function calls change the sequence of the program execution (Jump to function and then back) (pg 214)
  2. Decision(also called selection) – is used when a set of statements is executed only under certain conditions (pg 214-215)
  3. Repetition (also called loop or iteration) – used to perform the same set of statements a number of times (pg 215)

Combine Control Structures (Not in book, from CSC 200 class)

  • Each control structure has a single entry and a single exit point.
  • Two ways to combine control structures, stack or nest. See Section 6.4 for nested structures.
  • Figure 6.10 on page 229 shows example of stacked structures.
  • Figure 6.11 on page 230 shows example of nested structures.

ITP 134 – Chapter 6Mrs. EatonPage 1

Study Guide - Chapter 6 Control Structures

Flowchart Symbols (from CSC 200 class)

/ Terminal symbol. Starts and ends a program. Add Start at the beginning and End at the end. Use the function name in this symbol to start functions.
/ Decision symbol. Used to ask a question. Put the question inside the symbol.
/ Process symbol. Used for statements inside a block or sequence. Put the pseudocode statement inside the symbol.
/ Connector symbol. Used to connect flowcharts on the same page. Put A, B, C etc inside the symbol.
/ Off page symbol. Used to connect flowcharts on 2 pages. Put the page number inside the symbol.
/ Data symbol. Use for input or output.

ITP 134 – Chapter 6Mrs. EatonPage 1

Study Guide - Chapter 6 Control Structures

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 statement to execute only when a Boolean expression is true. If statement (general form) is: (see page 215-217) Use for true/false type questions.

if (expression)

{

Statements;

}

ITP 134 – Chapter 6Mrs. EatonPage 1

Study Guide - Chapter 6 Control Structures

Boolean Expressions and Relational Operators

The value of a Boolean expression can be either true or false. Boolean algebra is named after the English mathematician George Boole. (pg 217)

Relational Operators:(See table 6-1 on page 218)

  • > greater than;
  • < less than
  • >= greater or equal
  • <= less or equal
  • == equal to
  • != not equal

Putting it All Together

See Program 6-1, TestAverage.cpp for an example of if statement program. (pg 221)

Testing Colors

You can use == to test if colors are equivalent if both operands are declared as DWORD colors. (See pg 222-233)

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 the Boolean expression is false.

If-else statement (general form) is: (see page 224- 225) Use for true/false type questions.

if (expression)

{

/* executes if true */

Statements;

}

else

{

/* executes if false */
Statements;

}

In the Spotlight: A Number Guessing Game

  • Create a program where user has a single guess for a number using if-else statement. (pg 226 – 227)

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. (pg 228)

See Figure 6-12 Flowchart for Nested if statements and matching code on page 231 for good examples.

Programming Style and Nested Decision Structure

  • See page 234 in middle for wrong way to indent code.
  • See Figure 6-15 Alignment of if and else clauses to the professional way to indent code.

The if-else-if Statement

Nested if statements can become complex. C++ provides a special if-else-if statement which makes the logic easier to write. Use as an alternative to nested if statements. (Page 235) Here is the logic:

if (express1)

{

/* executes if true */

Statements;

}

else if (express2)

{

//executes if express2 is true
Statements;

}

// insert more else if clauses

else

{

// executes if express1 false

Statements;

}

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.

A repetition structure is also known as a loop. (page 237)

Condition-Controlled and Count-Controlled Loops

While and do-whilestatements are condition-controlled loops because they use a true/false condition to control the number of times it repeats. (page 238)

A for loop is a count-controlled loop because it repeats a specific number of times.

ITP 134 – Chapter 6Mrs. EatonPage 1

Study Guide - Chapter 6 Control Structures

ITP 134 – Chapter 6Mrs. EatonPage 1

Study Guide - Chapter 6 Control Structures

The while Loop

The while loops gets its name from the way it works. While a Boolean expression is true, do some task. (page 238) See the previous page for a diagram that shows the difference between a pretest while loop and a posttest do while loop.

The while Loop is a Pretest Loop

The while loop is known as a pretest loop, which means it tests the expression before performing the first iteration. (page 242)

Infinite Loops

Loops should always contain a way to terminate. If a loop does not have a way of stopping, it is called an infinite loop. (Not a good thing) An infinite loop continues to repeat until the program is interrupted. See page 245 for a sample of an infinite loop. The corrected code is on page 244.(page 245)

The do-while Loop: A Posttest Loop

The do-while loop is a posttest loop. This means that it will perform an iteration at least once before testing the Boolean expression. See the previous page for a diagram that shows the difference between a pretest while loop and a posttest do while loop. (page 246)

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

There are 4 ways to increment a value by 1 in C++: (page 248)

1. num = num +1;

2. num +=1;

3. num++;// called postfix mode

4. ++num;// called prefix mode

There are 4 ways to decrement a value by 1 in C++: (page 248)

1. num = num - 1;

2. num -=1;

3. num--;// called postfix mode

4. --num;// called prefix mode

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. (page 249)

The way a count-controlled loop works is simple. The loop keeps a count of the number of times it iterates, and when the count reaches a specified number, the loop stops.

You need 3 items to set up a for loop:

a) starting counter value

b) test value expression

c) increment or decrement value

In general the for loop syntax is (page 250)

for (j = start; j <= testvalue; j++)

{

Statements;

}

Compare this code with the while loop in Program 6-6 RandomBricksLoop.cpp (on page 242). Note: This code is not in the book. The result is the same for both programs:

for (numBricks = 10; numBricks > 0; numBricks--)
{

drawBrick(x,y);

}

Declaring the Counter Variable in the Initialization Expression

You can initialize and declare a counter variable in the for loop. For example simply add the int keyword: (page 252)

for (int count = 1; count <= 5; count++)

Using the Counter Variable in the Body of the Loop

You can use the counter variable in a calculation or other task in a for loop, but you should not change the value inside the loop. See Program 6-8 for an example (page 253)

Incrementing by Values Other Than 1

You can use the increment or decrement value in a for loop for any value you want. See Page 254 for an example of using 10 to increment.

Counting Backward by Decrementing the Counter Variable

You can decrement instead of incrementing a for loop variable. See example on page 254 and the previous page of this study guide.

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. (page 255)

See programs 6-9 and 6-10 for examples.

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. (page 260)

Truth Tables for Boolean Expressions
Not in Book

AND logical operator is true only when both are true.

A / B / A & B
F / F / F
F / T / F
T / F / F
T / T / T

OR logical operator false only when both are false.

A / B / A || B
F / F / F
F / T / T
T / F / T
T / T / T

NOT logical operator reverses Boolean value

A / !A
T / F
F / T

Precedence of Logical Operators

NOT has a higher precedence that the relational operators. AND and OR have a lower precedence than the relational operators. (page 264)

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. (page 266)

The switch statement is used for multiple choice type decisions.

See figure 6-28 (page 266) for a logical view of a switch statement. The general syntax for a switch statement is

switch(x)

{

case value1:

// executes when x=value1

Statements;

Break;

case value1:

// executes when x=value2

Statements;

Break;

// insert other case statements

cefault:

statements;

}

Important points about switch statements (page 268)

a)X value must be an integer, DWORD, or expression that gives an integer value.

b)Value that follows the case keyword must be an integer literal or constant. It cannot be a variable.

c)The break clause is optional, but if you do not use it the next case clause will also execute.

d)The default clause is optional, but it a smart exception handling statement.

e)Since default clause it at the end, it does not need a break statement.

6.11 Numeric Truth, Flags and Bool Variables

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

For example,

// flag if more than 5000 pts

bool grandMaster;

if (points > 5000)

{

grandMaster = true;

}

else

{

grandMaster = false;

}

Chapter 6 Programs

Program 6-1TestAverage.cpp (pages221-222)

  • This programprompts the user to enter 3 scores and then calculates the average.
  • This program shows a simple if statement. If the average is above 95% then a congratulations image is displayed as shown in Figure 6-6 on page 222.

Program 6-2 In the Spotlight: NumberGuessVersion1.cppA Number Guessing Game (pg 226 – 227)

  • This program gives a user a single guess for a number using anif-else statement. The program gives a message telling the user if the number guessed is correct or wrong only.

Program 6-3 In the Spotlight: NumberGuessVersion2.cppEnhancing the Number Guessing Game with Feedback (pg 232 – 233)

  • Enhance the guessing game program. This program gives a user a single guess for a number using nested if-else statements. The program gives a message telling user if the number guessed is correct, too high or too low.

Program 6-4 NumberGuess3.cpp (pg 235 – 236)

  • This program result is same as Program 6-3. This version uses an if-else-if statement instead of nested if statements. Enhance the guessing game program. This program gives a user a single guess for a number. The program gives a message telling user if the number guessed is correct, too high or too low.

Program 6-5 In the Spotlight: NumberGuess4.cppEnhancing the Number Guessing Game with a while loop (pg 240 – 242)

  • Enhance the guessing game program again. This program adds a while loop that repeatedly allows the user to enter guesses until the user get the right number. The program gives a message telling user if the number guessed is correct, too high or too low.

Program 6-6 RandomBricksLoop.cpp (pages 243-245)

  • This program uses a while loop to draw 10 bricks at random locations on the screen using the while loop.

Program 6-7 StarrySky.cpp (pages 251-252)

  • This program uses a for loop to draw 100 dots at random locations on the screen.

Program 6-8 LoopCircles.cpp (pages 253-254)

  • This program uses a for loop to draw 5 concentric circles at the screen’s center point.
  • Notice that the variable count is used to calculate the radius of the current circle in addition to keeping track of the loop iterations.

Program 6-9 TopRowBluePixels.cpp (pages 256-257)

  • This program uses a for loop to count the number of pure blue pixels in the top row of an image.

Program 6-10 CountBluePixels.cpp (pages 259-260)

  • This program enhanced the previous program. This program uses nested for loops to count the number of pure blue pixels in the top row of an image.

ITP 134 – Chapter 6Mrs. EatonPage 1

Study Guide - Chapter 6 Control Structures

ITP 134 – Chapter 6Mrs. EatonPage 1