c++programming

615
Introduction to Programming in C++ Seventh Edition Chapter 1: An Introduction to Programming

Upload: sardonicw

Post on 30-Nov-2015

286 views

Category:

Documents


0 download

DESCRIPTION

Programming with C++

TRANSCRIPT

Page 1: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 1:

An Introduction to Programming

Page 2: c++Programming

Chapter Objectives

• Define the terminology used in programming

• Explain the tasks performed by a programmer

• Understand the employment opportunities for programmers and software engineers

• Explain the history of programming languages

• Explain the sequence, selection, and repetition structures

• Write simple algorithms using the sequence, selection, and repetition structures

An Introduction to Programming with C++, Seventh Edition 2

Page 3: c++Programming

Programming a Computer

It is important to understand the relationship between the terms programs, programmers, and programming languages.

Programs - The directions that humans give to computers

Programmers - The people who create these directions

Programming Languages - Special languages used by programmers to communicate directions to a computer

An Introduction to Programming with C++, Seventh Edition 3

Page 4: c++Programming

The Programmer’s Job

• Programmers help solve computer problems

• Employee or freelance

• Typical steps involved

– Meet with user to determine problem

– Convert the problem into a program

– Test the program

– Provide user manual

An Introduction to Programming with C++, Seventh Edition 4

Page 5: c++Programming

An Introduction to Programming with C++, Seventh Edition 5

What Traits Should a Software Developer

Possess?

• Analytical skills

• Communication skills

• Creativity

• Customer-service skills

• Detail oriented

• Problem-solving skills

• Teamwork

• Technical skills

Page 6: c++Programming

Employment Opportunities

• Computer software engineer: designs an appropriate solution to a user’s problem

• Computer programmer: codes a computer solution

• Coding is the process of translating a computer solution into a language a computer can understand

• Some positions call for both engineering and programming

An Introduction to Programming with C++, Seventh Edition 6

Page 7: c++Programming

A Brief History of Programming Languages

There are many different types of programming languages. This chapter will discuss:

•Machine languages

•Assembly languages

•High-level procedure-oriented languages

•High-level object-oriented languages

An Introduction to Programming with C++, Seventh Edition 7

Page 8: c++Programming

An Introduction to Programming with C++, Seventh Edition 8

Machine Languages

• The first programmers had to write the program instructions using only combinations of 0s and 1s

– Example: 0000 0101 1100 0000

• Instructions written in 0s and 1s are called machine language or machine code

• Each type of machine has its own language

• Machine languages are the only way to communicate directly with the computer

• Programming in machine language: tedious and error-prone; requires highly trained programmers

Page 9: c++Programming

An Introduction to Programming with C++, Seventh Edition 9

Assembly Languages

• Assembly languages made writing code simpler than using only 0s and 1s

• Mnemonics – symbols used to represent the actual machine language instructions Example: 00000101 vs. BALR

• Assembly programs require an assembler to convert instructions into machine code

• Easier to write programs in assembly language

– But still tedious and requires highly trained programmers

Page 10: c++Programming

An Introduction to Programming with C++, Seventh Edition 10

High-Level Languages

• High-level languages allow programmers to use English-like instructions Example: taxAmount = total * taxRate

• Each high-level language instruction is equivalent to more than one machine language instruction

• Compilers translate high-level instructions into 0s and 1s (machine language)

• Interpreters translate the program line by line as the program is running

Page 11: c++Programming

An Introduction to Programming with C++, Seventh Edition 11

High-Level Languages (cont.)

• When writing a procedure-oriented program, the programmer concentrates on the major tasks that the program needs to perform

– Examples: COBOL, BASIC, C

• An object-oriented program requires the programmer to focus on the objects that the program can use to accomplish its goal

– Examples: C++, Visual Basic, Java, C#

• Object-oriented programs allow for an object to be created that can be reused in more than one program

Page 12: c++Programming

An Introduction to Programming with C++, Seventh Edition 12

Control Structures

All computer programs are written using one or more of three basic control structures: sequence, repetition, and selection. Another term used for control structures are logic structures, because they control the logic flow of the program. While in every program that is written the sequence structure will be used, in most all programs all three control structures will be used.

Page 13: c++Programming

An Introduction to Programming with C++, Seventh Edition 13

The Sequence Structure

• The sequence structure directs the computer to process the program instructions, one after another, in the order in which they are listed in the program

• An algorithm is a finite number of step-by-step instructions that accomplish a task

• Example: steps to pump gas at a self-service pump

Page 14: c++Programming

The Sequence Structure (cont.)

An Introduction to Programming with C++, Seventh Edition 14

Figure 1-1 An example of the sequence structure

Page 15: c++Programming

An Introduction to Programming with C++, Seventh Edition 15

The Selection Structure

• The selection structure directs the computer to make a decision (evaluate a condition), and then take an appropriate action based upon that decision

• The selection structure allows the programmer to evaluate data, therefore properly controlling the logic flow of the program

• Another name for the selection structure is the decision structure

• Example: stopping or going at a signal light

Page 16: c++Programming

The Selection Structure (cont.)

An Introduction to Programming with C++, Seventh Edition 16

Figure 1-2 An example of the selection structure

Page 17: c++Programming

An Introduction to Programming with C++, Seventh Edition 17

The Selection Structure (cont.)

Figure 1-3 Another example of the selection structure

Page 18: c++Programming

An Introduction to Programming with C++, Seventh Edition 18

The Repetition Structure

• The repetition structure, commonly called iteration or looping, directs the computer to repeat one or more program instructions until some condition is met

• This condition may be checked at the beginning or end of the set of instructions to be processed dependent upon the language being used

• The repetition structure allows the programmer to repeatedly process a set of instructions, while only typing them in once

Page 19: c++Programming

The Repetition Structure (cont.)

An Introduction to Programming with C++, Seventh Edition 19

Figure 1-4 Original algorithm and modified

algorithm showing the repetition structure

Page 20: c++Programming

An Introduction to Programming with C++, Seventh Edition 20

The Repetition Structure (cont.)

• What could you do if you do not know precisely how many steps separate Harold from the boxes as described on the bottom of page 9?

Page 21: c++Programming

The Repetition Structure (cont.)

An Introduction to Programming with C++, Seventh Edition 21

Figure 1-5 Algorithm showing the modified

condition in the repetition structure

Page 22: c++Programming

Summary

• Programs are step-by-step instructions that tell a computer how to perform a task

• Programmers use programming languages to communicate with the computer

• First programming languages were machine language using 0s and 1s

• Assembly languages followed, using mnemonics

• High-level languages can be used to created procedure-oriented or object-oriented programs

An Introduction to Programming with C++, Seventh Edition 22

Page 23: c++Programming

Summary (cont.)

• An algorithm is a finite number of step-by-step instructions that accomplish a task

• Algorithms utilize three basic control structures: sequence, selection, and repetition

• The sequence structure directs the computer to process the program instructions, one after another, in the order in which they are listed

• The selection structure directs the computer to make a decision (evaluate a condition), and then take an appropriate action based upon that decision

An Introduction to Programming with C++, Seventh Edition 23

Page 24: c++Programming

Summary (cont.)

• The repetition structure, commonly called iteration or looping, directs the computer to repeat one or more program instructions until some condition is met

• The sequence structure is used in all programs

• Most programs also contain both the selection and repetition structures

An Introduction to Programming with C++, Seventh Edition 24

Page 25: c++Programming

Lab 1-1: Stop and Analyze

• A local business employs five salespeople and pays a 3% bonus on a salesperson’s sales

• Your task is to create a program that calculates the amount of each salesperson’s bonus

• The program should print each salesperson’s name and bonus amount

An Introduction to Programming with C++, Seventh Edition 25

Page 26: c++Programming

An Introduction to Programming with C++, Seventh Edition 26

Lab 1-2: Plan and Create

• Using only the instructions shown below, create an algorithm that shows the steps an instructor takes when grading a test that contains 25 questions

Page 27: c++Programming

An Introduction to Programming with C++, Seventh Edition 27

Lab 1-3: Modify

• Modify the algorithm shown in Lab 1-1 so that it gives a 3.5% bonus to salespeople selling more than $2,000

• All other salespeople should receive a 3% bonus

Page 28: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 2:

Beginning the Problem-Solving Process

Page 29: c++Programming

• Explain the problem-solving process used to create a computer program

• Analyze a problem

• Complete an IPO chart

• Plan an algorithm using pseudocode and flowcharts

• Desk-check an algorithm

Chapter Objectives

2 An Introduction to Programming with C++, Seventh Edition

Page 30: c++Programming

• People solve hundreds of simple problems every day without thinking about how they do it

• Understanding the thought process involved can help in solving more complex problems

• You can also use a similar process to design a computer solution to a problem (computer program)

Problem Solving

3 An Introduction to Programming with C++, Seventh Edition

Page 31: c++Programming

• First step in solving a problem: analyze it

– Example: paying and mailing a bill

• Next, you plan, review, implement, and evaluate the solution

• After this, it may be necessary to modify the solution

Solving Everyday Problems

4 An Introduction to Programming with C++, Seventh Edition

Page 32: c++Programming

Solving Everyday Problems (cont’d.)

Figure 2-1 Summary of the analysis and planning steps for

the bill paying problem

5 An Introduction to Programming with C++, Seventh Edition

Page 33: c++Programming

Solving Everyday Problems (cont’d.)

Figure 2-2 Modified algorithm for the bill paying problem

6 An Introduction to Programming with C++, Seventh Edition

Page 34: c++Programming

• A similar process to everyday problem solving is used to create computer programs

• A computer program is a solution implemented on a computer

• There are six steps to creating a computer solution to a problem

Creating Computer Solutions to Problems

7 An Introduction to Programming with C++, Seventh Edition

Page 35: c++Programming

Creating Computer Solutions to Problems

(cont’d.)

Figure 2-3 How to create a computer solution to a problem

8 An Introduction to Programming with C++, Seventh Edition

Page 36: c++Programming

• It is essential to understand a problem before creating a solution to it

• Analyze a problem to:

– Determine the goal of solving it (Output)

– Determine the items needed to achieve that goal (Input)

• Always search first for the output

Step 1−Analyzing the Problem

9 An Introduction to Programming with C++, Seventh Edition

Page 37: c++Programming

Step 1−Analyzing the Problem (cont’d.)

Figure 2-4 Problem specification for Treyson Mobley

10 An Introduction to Programming with C++, Seventh Edition

Page 38: c++Programming

• Some programmers use an IPO chart to organize and summarize the results of a problem analysis

– IPO: Input, processing, and output

Step 1−Analyzing the Problem (cont’d.)

Figure 2-5 Partially completed IPO chart

showing the input and output items

11 An Introduction to Programming with C++, Seventh Edition

Page 39: c++Programming

• Several readings of the problem may be necessary to fully understand the problem

• Cross out irrelevant information in the problem description

Hints for Analyzing Problems

Figure 2-6 Problem specification with

unimportant information crossed out

12 An Introduction to Programming with C++, Seventh Edition

Page 40: c++Programming

• Some problem specifications contain incomplete information

Hints for Analyzing Problems (cont’d.)

Figure 2-7 Problem specification that does

not contain enough information

13 An Introduction to Programming with C++, Seventh Edition

Page 41: c++Programming

• Distinguish between information that is missing and information that is implied

Hints for Analyzing Problems (cont’d.)

Figure 2-8 Problem specification in

which the input is not explicitly stated

14 An Introduction to Programming with C++, Seventh Edition

Page 42: c++Programming

• Algorithm: set of instructions that will transform the problem’s input into its output

– Record in the Processing column of the IPO chart

– Can be written as pseudocode or a flowchart

• Pseudocode: tool programmers use to help plan an algorithm

– Short English statements

– Not standardized

– Not understandable by a computer

Step 2−Planning the Algorithm

15 An Introduction to Programming with C++, Seventh Edition

Page 43: c++Programming

Step 2−Planning the Algorithm (cont’d.)

Figure 2-9 Problem specification and IPO

chart for the Treyson Mobley problem

16 An Introduction to Programming with C++, Seventh Edition

Page 44: c++Programming

• Flowcharts are also used to plan an algorithm

– Use standardized symbols

– Symbols connected with flowlines

– Oval: start/stop symbol

• Represents beginning and end of algorithm

– Rectangle: process symbol

• Represents tasks such as calculations

– Parallelogram: input/output symbol

• Represents I/O tasks

Step 2−Planning the Algorithm (cont’d.)

17 An Introduction to Programming with C++, Seventh Edition

Page 45: c++Programming

Figure 2-10 Figure 2-9’s algorithm in flowchart form

18 An Introduction to Programming with C++, Seventh Edition

Step 2−Planning the Algorithm (cont’d.)

Page 46: c++Programming

• A problem can have more than one solution

Step 2−Planning the Algorithm (cont’d.)

Figure 2-11 A different solution to the

Treyson Mobley problem (pseudocode)

19 An Introduction to Programming with C++, Seventh Edition

Page 47: c++Programming

• Processing item: an intermediate value (neither input nor output) the algorithm uses to transform input into output

Step 2−Planning the Algorithm (cont’d.)

Figure 2-11 A different solution to the Treyson

Mobley problem (flowchart)

20 An Introduction to Programming with C++, Seventh Edition

Page 48: c++Programming

Step 3−Desk-Checking the Algorithm

• Desk-checking an algorithm verifies that it is correct

– Refers to checking an algorithm by hand, rather than with a computer

– Also called hand-tracing

• Choose sample data and manually compute the expected output value

• Creating a desk-check table can be helpful

21 An Introduction to Programming with C++, Seventh Edition

Page 49: c++Programming

Step 3−Desk-Checking the Algorithm

(cont’d.)

Figure 2-12 Manual tip calculation for the first desk-check

22 An Introduction to Programming with C++, Seventh Edition

Page 50: c++Programming

Step 3−Desk-Checking the Algorithm

(cont’d.)

Figure 2-13 Treyson Mobley solution and

partially completed desk-check table

23 An Introduction to Programming with C++, Seventh Edition

Page 51: c++Programming

Step 3−Desk-Checking the Algorithm

(cont’d.)

Figure 2-14 Input values entered in the desk-check table

Figure 2-15 Processing item’s value

entered in the desk-check table

Figure 2-16 Output value entered in the desk-check table

24 An Introduction to Programming with C++, Seventh Edition

Page 52: c++Programming

Step 3−Desk-Checking the Algorithm

(cont’d.)

Figure 2-17 Manual tip calculation for

the second desk-check

25 An Introduction to Programming with C++, Seventh Edition

Page 53: c++Programming

Figure 2-19 Value of the second desk-check’s

processing item entered in the desk-check table

Figure 2-20 Value of the second desk-check’s

output item entered in the desk-check table

Figure 2-18 Second set of input values

entered in the desk-check table

26 An Introduction to Programming with C++, Seventh Edition

Step 3−Desk-Checking the Algorithm

(cont’d.)

Page 54: c++Programming

• Valid data: data that the algorithm is expecting the user to enter

• Invalid data: data that the algorithm is not expecting the user to enter

• You should test an algorithm with invalid data

– Users may make mistakes when entering data

Step 3−Desk-Checking the Algorithm

(cont’d.)

27 An Introduction to Programming with C++, Seventh Edition

Page 55: c++Programming

The Gas Mileage Problem

Figure 2-21 Problem specification for the gas mileage problem

28 An Introduction to Programming with C++, Seventh Edition

Page 56: c++Programming

The Gas Mileage Problem (cont’d.)

• Plan the algorithm with an IPO chart

Figure 2-22 IPO chart for the gas mileage problem

29 An Introduction to Programming with C++, Seventh Edition

Page 57: c++Programming

• Then desk-check the algorithm

The Gas Mileage Problem (cont’d.)

Figure 2-23 Desk-check table for the gas mileage problem

30 An Introduction to Programming with C++, Seventh Edition

Page 58: c++Programming

• Problem solving typically involves analyzing the problem and then planning, reviewing, implementing, evaluating, and modifying (if necessary) the solution

• Programmers use tools (IPO charts, pseudocode, flowcharts) to help them analyze problems and develop algorithms

• The first step in problem solving is to analyze the problem

– First determine the output and then the input

Summary

31 An Introduction to Programming with C++, Seventh Edition

Page 59: c++Programming

• The second step is to plan the algorithm

– Write the steps that will transform the input into the output

– Most algorithms begin with entering input data, then processing the data, then displaying the output

• The third step is to desk-check the algorithm

– Choose sample data and manually compute the expected output

– Create a desk-check table to fill in values step by step

Summary (cont’d.)

32 An Introduction to Programming with C++, Seventh Edition

Page 60: c++Programming

• Aiden Nelinski is paid every Friday and will receive either a 2.0% or 2.5% raise next week

• He wants a program that calculates and displays the amount of his new weekly pay

Lab 2-1: Stop and Analyze

Figure 2-26 IPO chart for Lab 2-1

33 An Introduction to Programming with C++, Seventh Edition

Page 61: c++Programming

• Create an algorithm for the manager of the Lakeview Hotel

Lab 2-2: Plan and Create

Figure 2-30 Completed IPO chart for Lab 2-2

34 An Introduction to Programming with C++, Seventh Edition

Page 62: c++Programming

• Each guest of the Lakeview Hotel pays an entertainment tax, which is a percentage of the room charge only

• Modify the IPO chart in Figure 2-30

• Desk-check the algorithm twice using the given values

Lab 2-3: Modify

35 An Introduction to Programming with C++, Seventh Edition

Page 63: c++Programming

• An algorithm is given to calculate and display an annual property tax

• Desk-check the algorithm three times using the given values

Lab 2-4: Desk-Check

Figure 2-36 IPO chart for Lab 2-4

36 An Introduction to Programming with C++, Seventh Edition

Page 64: c++Programming

• An algorithm is given to calculate and display the average of three numbers but is incorrect

• Find and correct the errors in the algorithm

Lab 2-5: Debug

Figure 2-37 IPO chart for Lab 2-5

Figure 2-42 Corrected algorithm for Lab 2-5

37 An Introduction to Programming with C++, Seventh Edition

Page 65: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 3:

Variables and Constants

Page 66: c++Programming

• Distinguish among a variable, a named constant, and a literal constant

• Explain how data is stored in memory

• Select an appropriate name, data type, and initial value for a memory location

• Declare a memory location in C++

An Introduction to Programming with C++, Seventh Edition

Chapter Objectives

2

Page 67: c++Programming

• After Step 3, programmer has an algorithm and has desk-checked it

• The fourth step in the process is coding the algorithm into a program

• The step begins by assigning a descriptive name, data type, and (optionally) initial value to each unique input, processing, and output item in the IPO chart

• These are used to store the item in the computer’s internal memory

An Introduction to Programming with C++, Seventh Edition

Beginning Step 4 in the Problem-Solving

Process

3

Page 68: c++Programming

• Computer’s internal memory is composed of memory locations, each with a unique numeric address

• Similar to collection of storage bins

• Each address can store one item at a time

• Address can contain numbers, text, or program instructions

• To use a memory location, programmer must reserve the address, called declaring

An Introduction to Programming with C++, Seventh Edition

Internal Memory

4

Page 69: c++Programming

• Declaring a memory location is done with an instruction that assigns a name, data type, and (optional) initial value

• The name allows the programmer to refer to the memory location elsewhere in the program using a descriptive word, rather than the numeric address

• The data type indicates what type of information the address will store (e.g., number or text)

An Introduction to Programming with C++, Seventh Edition

Internal Memory (cont’d.)

5

Page 70: c++Programming

• Two types of memory locations can be declared: variables and named constants

• Variables are memory locations whose values can change during runtime (when the program is running)

• Most memory locations are variables

• Named constants are memory locations whose values cannot change during program execution

An Introduction to Programming with C++, Seventh Edition

Internal Memory (cont’d.)

6

Page 71: c++Programming

An Introduction to Programming with C++, Seventh Edition

Internal Memory (cont’d.)

Figure 3-1 Illustration of storage bins

7

Page 72: c++Programming

• Name (identifier) assigned to a memory location should be descriptive

• Should help the programmer/other programmers remember/understand the memory location’s purpose

• Should be as short as possible while still being descriptive (especially if referenced often)

• Short names are easier to read and result in more concise code

An Introduction to Programming with C++, Seventh Edition

Selecting a Name for a Memory Location

8

Page 73: c++Programming

• Rules for memory location names in C++

– Name must begin with a letter and contain only letters, numbers, and the underscore character

– No punctuation marks, spaces, or other special characters (such as $ or %) are allowed

– Cannot be a keyword (word that has special meaning in C++)

– Names are case sensitive

• Example: discount is different from DISCOUNT and from Discount

An Introduction to Programming with C++, Seventh Edition

Selecting a Name for a Memory Location

(cont’d.)

9

Page 74: c++Programming

• Most programmers use uppercase letters for named constants and lowercase for variables

– Example: PI (constant), radius (variable)

• If constants contain more than one word, separate words with underscores

– Example: TAX_RATE

• If variables contain more than one word, capitalize the first letter of each word after the first (called camel case)

– Example: adjustedGrossIncome

An Introduction to Programming with C++, Seventh Edition

Selecting a Name for a Memory Location

(cont’d.)

10

Page 75: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 3-2 How to name a memory location in C++

11

Selecting a Name for a Memory Location

(cont’d.)

Page 76: c++Programming

An Introduction to Programming with C++, Seventh Edition

Revisiting the Treyson Mobley Problem

Figure 3-3 Problem specification, IPO chart,

and desk-check table from Chapter 2

12

Page 77: c++Programming

• IPO chart contains five input, processing, and output items

• Five memory locations are needed to store the values of the items

• Memory locations will be variables since their values will change during runtime

An Introduction to Programming with C++, Seventh Edition

Revisiting the Treyson Mobley Problem

(cont’d.)

13

Page 78: c++Programming

An Introduction to Programming with C++, Seventh Edition

Revisiting the Treyson Mobley Problem

(cont’d.)

Figure 3-4 Names of the variables for the Treyson Mobley problem

14

Page 79: c++Programming

• Memory locations come in different types and sizes

• Type and size you choose depends on the item you want to store

• A memory location will only accept an item that matches its data type

• Data type of a memory location is determined by the programmer when declaring the location

An Introduction to Programming with C++, Seventh Edition

Selecting a Data Type for a Memory

Location

15

Page 80: c++Programming

• Fundamental data types are basic data types built into C++

– Also called primitive or built-in data types

– Include short, int, float, double, bool, and char

• bool data type stores Boolean values (true and false)

• short and int types store integers (numbers without a decimal place)

– Differences are range of values and memory used (int

has the greater of both)

An Introduction to Programming with C++, Seventh Edition

Selecting a Data Type for a Memory

Location (cont’d.)

16

Page 81: c++Programming

• float and double types store real numbers (numbers with a decimal place)

– Differences are range of values, precision, and memory used (double has the greater of each)

• char type stores characters (letter, symbol, or number that will not be used in a calculation)

– Only one character stored at a time

• string data type is a user-defined data type (defined with a class, or group of instructions)

– Can store zero or more characters

An Introduction to Programming with C++, Seventh Edition

Selecting a Data Type for a Memory

Location (cont’d.)

17

Page 82: c++Programming

An Introduction to Programming with C++, Seventh Edition

Selecting a Data Type for a Memory

Location (cont’d.)

Figure 3-5 Most commonly used data types in C++

18

Page 83: c++Programming

• 1 byte = 8 bits

• 1 kilobyte (K / Kb) = 2^10 bytes = 1,024 bytes

• 1 megabyte (M / MB) = 2^20 bytes = 1,048,576 bytes

• 1 gigabyte (G / GB) = 2^30 bytes = 1,073,741,824 bytes

• 1 terabyte (T / TB) = 2^40 bytes = 1,099,511,627,776 bytes

• 1 petabyte (P / PB) = 2^50 bytes = 1,125,899,906,842,624 bytes

• 1 exabyte (E / EB) = 2^60 bytes = 1,152,921,504,606,846,976 bytes

An Introduction to Programming with C++, Seventh Edition 19

Page 84: c++Programming

An Introduction to Programming with C++, Seventh Edition

Selecting a Data Type for a Memory

Location (cont’d.)

Figure 3-6 Data type assigned to each

variable for the Treyson Mobley problem

20

Page 85: c++Programming

• Numbers represented in internal memory using binary (base 2) number system (two digits, 0 and 1)

• We are used to the decimal (base 10) number system (ten digits, 0 through 9)

• Character data is stored using ASCII codes

– Eight-bit codes (bit = binary digit, 0 or 1)

– Upper- and lowercase versions of letters have distinct codes

• Computer distinguishes between numbers and ASCII codes based on data type

An Introduction to Programming with C++, Seventh Edition

How Data Is Stored in Internal Memory

21

Page 86: c++Programming

An Introduction to Programming with C++, Seventh Edition

How Data Is Stored in Internal Memory

(cont’d.)

Figure 3-7 How to use the decimal (base 10) number system

22

Page 87: c++Programming

An Introduction to Programming with C++, Seventh Edition

How Data Is Stored in Internal Memory

(cont’d.)

Figure 3-8 How to use the binary (base 2) number system

23

Page 88: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 3-9 Partial ASCII chart

24

How Data Is Stored in Internal Memory

(cont’d.)

Page 89: c++Programming

• Setting an initial value for a variable or named constant is called initializing

• Required for constants; recommended for variables

• Memory locations are usually initialized with a literal constant (item of data that can appear in a program instruction and be stored in memory)

• Data type of literal constant should match data type of memory location it is assigned to

An Introduction to Programming with C++, Seventh Edition

Selecting an Initial Value for a Memory

Location

25

Page 90: c++Programming

• Numeric literal constants initialize short, int, float, and double data types

– Can contain digits 0 through 9, +, -, ., and e or E (for scientific notation)

• Character literal constants initialize char data types

– Consist of one character in single quotation marks

• String literal constants initialize string data types

– Zero or more characters enclosed in double quotation marks

– Empty string (“”) is a valid string literal constant

An Introduction to Programming with C++, Seventh Edition

Selecting an Initial Value for a Memory

Location (cont’d.)

26

Page 91: c++Programming

• Before assigning initial value to a memory location, computer checks that value’s data type matches location’s data type

• If they don’t match, computer performs implicit type conversion to match them

– If initial value is converted to type that holds larger numbers, value is promoted

– If initial value is converted to type that only holds smaller numbers, value is demoted

• Promoting will not usually have adverse effects, but demoting can (information is lost)

An Introduction to Programming with C++, Seventh Edition

Selecting an Initial Value for a Memory

Location (cont’d.)

27

Page 92: c++Programming

• Important to initialize memory locations with values of the same data type

• Named constants should be initialized with the value they will hold for the duration of the program

• Variables whose initial values are not known should still be initialized

– short and int types usually initialized to 0

– float and double types usually initialized to 0.0

– string types usually initialized to empty string (“”)

– bool types initialized to either true or false

An Introduction to Programming with C++, Seventh Edition

Selecting an Initial Value for a Memory

Location (cont’d.)

28

Page 93: c++Programming

An Introduction to Programming with C++, Seventh Edition

Selecting an Initial Value for a Memory

Location (cont’d.)

Figure 3-10 Initial values for the variables

in the Treyson Mobley problem

29

Page 94: c++Programming

• Variables and named constants are declared using a statement (C++ instruction)

• A statement that declares a variable causes the computer to set aside a memory location with the given name, data type, and initial value

• Statements must follow correct syntax (rules of a programming language)

• In C++, all statements must end with a semicolon

An Introduction to Programming with C++, Seventh Edition

Declaring a Memory Location

30

Page 95: c++Programming

• When declaring variables, a data type and name must be provided

• Syntax for declaring a variable in C++ – dataType variableName [= initialValue];

• After variable is declared, you use its name to refer to it later in the program

• Initial value is optional but recommended

• If variable is not initialized, it contains the previous value of that memory location, which may be the wrong type (called a garbage value)

An Introduction to Programming with C++, Seventh Edition

Declaring a Memory Location (cont’d.)

31

Page 96: c++Programming

• Syntax for declaring a named constant in C++

– const dataType constantName = value;

• The const keyword indicates that the memory location is a named constant (value cannot be changed during runtime)

• Initial value required for constants, unlike variables

• As with variables, after declaring a constant, you can use its name to refer to it later in the program

An Introduction to Programming with C++, Seventh Edition

Declaring a Memory Location (cont’d.)

32

Page 97: c++Programming

• Several advantages to using named constants when appropriate

– Make program more self-documenting (meaningful words in place of numbers)

– Value cannot be inadvertently changed during runtime

– Typing a name is less error-prone than a long number

– Mistyping a constant’s name will trigger a compiler error; mistyping a number will not

– If the constant needs to be changed when modifying the program, it only needs to be changed in one place

An Introduction to Programming with C++, Seventh Edition

Declaring a Memory Location (cont’d.)

33

Page 98: c++Programming

An Introduction to Programming with C++, Seventh Edition

Declaring a Memory Location (cont’d.)

Figure 3-11 How to declare a variable in C++

34

Page 99: c++Programming

An Introduction to Programming with C++, Seventh Edition

Declaring a Memory Location (cont’d.)

Figure 3-12 C++ declaration statements for the

variables in the Treyson Mobley problem

35

Page 100: c++Programming

An Introduction to Programming with C++, Seventh Edition

Declaring a Memory Location (cont’d.)

Figure 3-13 How to declare a named constant in C++

36

Page 101: c++Programming

• Fourth step in problem-solving process is coding the algorithm

• Memory location is declared for each input, processing, and output item in IPO chart

• Numeric data is stored in computer’s internal memory using binary number system

• Memory locations store one item at a time

• Memory location’s data type determines how a value is stored and interpreted when retrieved

An Introduction to Programming with C++, Seventh Edition

Summary

37

Page 102: c++Programming

• Two types of memory locations: variables and named constants

• Memory locations are declared using a statement that assigns a name, data type, and initial value

• Initial value required for named constants but optional for variables (though recommended)

• Most memory locations initialized with literal constants, except bool (initialized with keywords true or false)

An Introduction to Programming with C++, Seventh Edition

Summary (cont’d.)

38

Page 103: c++Programming

• Data type of literal constant assigned to memory location should be same as memory location’s type

• If types don’t match, implicit type conversion is used to either promote or demote so they match

• Promoting doesn’t usually cause problems, but demoting can

• Syntax for declaring variables

– dataType variableName [= initialValue];

• Syntax for declaring named constants

– const dataType constantName = value;

An Introduction to Programming with C++, Seventh Edition

Summary (cont’d.)

39

Page 104: c++Programming

An Introduction to Programming with C++, Seventh Edition

Lab 3-1: Stop and Analyze

Figure 3-14 Problem specification, IPO chart,

and desk-check table for Lab 3-1

40

Page 105: c++Programming

An Introduction to Programming with C++, Seventh Edition

Lab 3-2: Plan and Create

Figure 3-15 Problem specification for Lab 3-2

41

Page 106: c++Programming

• Modify the IPO chart in Figure 3-17 so that it includes the radius squared as a processing item

An Introduction to Programming with C++, Seventh Edition

Lab 3-3: Modify

Figure 3-17 Completed IPO chart for Lab 3-2

42

Page 107: c++Programming

• Using the IPO chart modified in Lab 3-3, modify the manual calculations and desk-check tables shown in Figures 3-18 and 3-19

An Introduction to Programming with C++, Seventh Edition

Lab 3-4: Desk-Check

Figure 3-18 Manual area calculations for the two desk-checks

Figure 3-19 Completed desk-check table for Lab 3-2

43

Page 108: c++Programming

• Correct the C++ instructions shown in Figure 3-21

– The memory locations will store real numbers

• Find and correct the errors in the algorithm

An Introduction to Programming with C++, Seventh Edition

Lab 3-5: Debug

Figure 3-21 IPO chart information and C++ instructions for Lab 3-5

44

Page 109: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 4:

Completing the Problem-Solving Process

Page 110: c++Programming

• Get numeric and character data from the keyboard

• Display information on the computer screen

• Write arithmetic expressions

• Type cast a value

• Write an assignment statement

• Code the algorithm into a program

• Desk-check a program

• Evaluate and modify a program

An Introduction to Programming with C++, Seventh Edition

Objectives

2

Page 111: c++Programming

• The fourth step in the problem-solving process is to code algorithm into a program

• Begin by declaring a memory location for each input, processing, and output value in IPO chart

• Optionally initialize each value (highly preferred)

• Next, you code the instructions for the algorithm

An Introduction to Programming with C++, Seventh Edition

Finishing Step 4 in the Problem-Solving

Process

3

Page 112: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-1 Problem specification, IPO chart

information, and variable declaration

4

Finishing Step 4 in the Problem-Solving

Process (cont’d.)

Page 113: c++Programming

• C++ uses stream objects to perform input/output operations

• A stream is a sequence of characters

• The cin object is used to obtain information from the keyboard (program pauses while user enters data)

• The extraction operator (>>) takes information out of cin object and stores it in internal memory

– Syntax: cin >> variableName;

An Introduction to Programming with C++, Seventh Edition

Getting Data from the Keyboard

5

Page 114: c++Programming

An Introduction to Programming with C++, Seventh Edition

Getting Data from the Keyboard (cont’d.)

Figure 4-2 Relationship among the keyboard, cin object,

extraction operator, and internal memory

6

Page 115: c++Programming

An Introduction to Programming with C++, Seventh Edition

Getting Data from the Keyboard (cont’d.)

Figure 4-3 How to use cin and >> to

get numeric or character data

7

Page 116: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-4 Input statements for

the Treyson Mobley problem

8

Getting Data from the Keyboard (cont’d.)

Page 117: c++Programming

• You use a prompt (message) to let the user know what data is to be entered

• The cout object is used with the insertion operator (<<) to display information on the screen

• Information can be any combination of literal constants, named constants, and variables

• Multiple items can be printed in the same statement

– Syntax: cout << item1 [<< item2 << itemN];

– Part in brackets is optional

An Introduction to Programming with C++, Seventh Edition

Displaying Messages on the Computer

Screen

9

Page 118: c++Programming

• A stream manipulator is used to manipulate (manage) the characters in an input or output string

• endl is a stream manipulator that advances the cursor to the next line on the screen

– Equivalent to pressing the Enter key

(carriage return and line feed)

An Introduction to Programming with C++, Seventh Edition

Displaying Messages on the Computer

Screen (cont’d.)

10

Page 119: c++Programming

An Introduction to Programming with C++, Seventh Edition

Displaying Messages on the Computer

Screen (cont’d.)

Figure 4-5 How to use the cout object

11

Page 120: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-6 Prompts and output statement

for the Treyson Mobley problem

12

Displaying Messages on the Computer

Screen (cont’d.)

Page 121: c++Programming

• You can evaluate arithmetic expressions in C++ using arithmetic operators

• Operators are negation (-), addition (+), subtraction (-), multiplication (*), division (/), and modulus (%)

• Negation and subtraction use the same symbol, but negation is a unary operator (one operand) and subtraction is a binary operator (two operands)

• Modulus gives remainder when dividing two integers

An Introduction to Programming with C++, Seventh Edition

Arithmetic Operators in C++

13

Page 122: c++Programming

• Each operator has a precedence: determines in which order operators in an expression are evaluated

• Operators with lower-precedence numbers are evaluated before higher ones

• Parentheses have lowest-precedence number, so they can be used to override precedence order

• Operators with the same precedence number are evaluated from left to right

An Introduction to Programming with C++, Seventh Edition

Arithmetic Operators in C++ (cont’d.)

14

Page 123: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-7 Standard arithmetic operators and their order of precedence

15

Arithmetic Operators in C++ (cont’d.)

Page 124: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-8 Expressions containing more than one

operator having the same precedence

16

Arithmetic Operators in C++ (cont’d.)

Page 125: c++Programming

• Recall that the compiler will implicitly promote or demote data types to match when possible

• Sometimes it is necessary to explicitly cast from one data type into another

– Example: dividing two integers gives the result of integer division (no remainder), but you would really like a double result

– If one or both of the integers is a literal, you can cast it to a double by adding .0 to the end of it

– If both are variables, you must use the static_cast operator

An Introduction to Programming with C++, Seventh Edition

Type Conversions in Arithmetic

Expressions

17

Page 126: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-9 Examples of expressions that

require implicit type conversions

18

Type Conversions in Arithmetic

Expressions (cont’d.)

Page 127: c++Programming

• Used to explicitly convert data from one data type to another

• Called an explicit type conversion or type cast

• Syntax: static_cast<dataType>(data)

– data can be a literal constant, named constant, or variable

– dataType is the data type to which you want the data converted

An Introduction to Programming with C++, Seventh Edition

The static_cast Operator

19

Page 128: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-10 How to use the static_cast operator

20

The static_cast Operator (cont’d.)

Page 129: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-10 How to use the static_cast operator (cont’d.)

21

The static_cast Operator (cont’d.)

Page 130: c++Programming

• You use an assignment statement to assign a value to a variable while a program is running

• Syntax: variableName = expression

– The = symbol is the assignment operator

• Tells computer to evaluate expression on right side of assignment operator and store result in variable on left side of the operator

– expression can include one or more literal constants, named constants, variables, or arithmetic operators

An Introduction to Programming with C++, Seventh Edition

Assignment Statements

22

Page 131: c++Programming

• Data type of expression in an assignment statement must match data type of the variable

• If they don’t match, compiler will use implicit type casting to get them to match

– Doesn’t always produce correct result

– Better to explicitly cast to correct data type yourself

• Remember:

– Declaration statement creates a new variable

– Assignment statement assigns a new value to an existing variable

An Introduction to Programming with C++, Seventh Edition

Assignment Statements (cont’d.)

23

Page 132: c++Programming

An Introduction to Programming with C++, Seventh Edition

Assignment Statements (cont’d.)

Figure 4-11 How to write an assignment statement

24

Page 133: c++Programming

An Introduction to Programming with C++, Seventh Edition

Assignment Statements (cont’d.)

Figure 4-11 How to write an assignment statement (cont’d.)

25

Page 134: c++Programming

An Introduction to Programming with C++, Seventh Edition

Figure 4-12 Calculation statements

for the Treyson Mobley problem

26

Assignment Statements (cont’d.)

Page 135: c++Programming

• Allow you to abbreviate assignment statements that contain an arithmetic operator

• Statement must be of the form variableName = variableName arithmeticOperator value

• Abbreviated as variableName arithmeticOperator = value

– Example: price = price*1.05; can be abbreviated as price *= 1.05;

• Most common operators are += , -= , *= , /= , and %=

An Introduction to Programming with C++, Seventh Edition

Arithmetic Assignment Operators

27

Page 136: c++Programming

An Introduction to Programming with C++, Seventh Edition 28

Figure 4-13 How to use an arithmetic assignment operator

Arithmetic Assignment Operators (cont’d)

Page 137: c++Programming

• Fifth step is to desk-check the program to make sure instructions were translated correctly

• You should desk-check the program using sample data used to desk-check the algorithm

• Results of both desk-checks should be the same

• First, place names of the declared memory locations in a new desk-check table along with each memory location’s initial value

• Next, desk-check remaining C++ instructions in order, recording any changes made to the variables

An Introduction to Programming with C++, Seventh Edition

Step 5–Desk-Check the Program

29

Page 138: c++Programming

An Introduction to Programming with C++, Seventh Edition

Step 5–Desk-Check the Program (cont’d.)

Figure 4-15 Variable names and initial values entered in the

program’s desk-check table

Figure 4-14 Algorithm’s desk-check table from Chapter 2

30

Page 139: c++Programming

An Introduction to Programming with C++, Seventh Edition

Step 5–Desk-Check the Program (cont’d.)

Figure 4-16 Input values entered in the program’s desk-check table

Figure 4-17 Desk-check table showing the result of the

total bill without liquor charge calculation

31

Page 140: c++Programming

An Introduction to Programming with C++, Seventh Edition

Step 5–Desk-Check the Program (cont’d.)

Figure 4-18 Desk-check table showing the result of the tip calculation

Figure 4-19 Program’s desk-check table showing the

results of the second desk-check

32

Page 141: c++Programming

• Final step in the problem-solving process

• You evaluate a program by running the program on the computer and entering the sample data used when desk-checking the program

• If evaluation reveals errors (known as bugs), they must be fixed

• Process of locating and fixing errors is called debugging

• Two types of bugs: syntax errors and logic errors

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

33

Page 142: c++Programming

• Syntax errors result from breaking programming language’s rules; cause compiler errors

• Logic errors don’t cause compiler errors; can be hard to identify

– Example: entering instructions in the wrong order

• Need a text editor to enter C++ instructions

• Instructions are called source code and are saved in source files with extension .cpp

• Need a compiler to translate source code into machine code (also called object code)

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

34

Page 143: c++Programming

• Compiler saves object code in object files with extension .obj

• Linker combines .obj files with other machine code necessary to run the program and produces an executable file with extension .exe

• An IDE (integrated development environment) is a development tool that contains both an editor and compiler

• A command-line compiler contains only the compiler and requires a separate editor to enter source code

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

35

Page 144: c++Programming

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

Figure 4-20 Process by which source code

is translated into executable code

36

Page 145: c++Programming

• A comment is a form of internal documentation; written by placing // in front of the comment text

– Ignored by the compiler

– Considered good programming practice; makes code more readable

• A #include directive allows you to merge the source code in one file with that in another file

• The #include <iostream> is required when using the cin or cout stream objects

– Not a statement, so no semicolon needed at the end

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

37

Page 146: c++Programming

• A using directive tells the compiler where in internal memory it can find definitions of C++ keywords and classes like double or string

• The using namespace std; directive indicates that the definitions of the standard C++ keywords and classes are located in the std (standard) namespace

– Is a statement, so semicolon required at the end

• A namespace is a special area in internal memory

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

38

Page 147: c++Programming

• A function is a block of code that performs a task

• Functions have parentheses following their name (Example: main())

• Some functions require information between the parentheses; others do not

• Every C++ program has one (and only one) main function; this is where program execution begins

• Some functions return a value, and the data type they return appears to the left of the function name

– Example: int main()

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

39

Page 148: c++Programming

• Other functions do not return a value, and void appears to the left of the function name

• The return type, name, and parameters (information in parentheses) constitute the function header, which marks the beginning of the function

• After the function header, you enter the function’s code

• You enclose a function’s code in a set of braces ({})

• The code between the braces is called the function body

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

40

Page 149: c++Programming

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

Figure 4-21 Treyson Mobley program

41

Page 150: c++Programming

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

Figure 4-21 Treyson Mobley program (cont’d.)

42

Page 151: c++Programming

An Introduction to Programming with C++, Seventh Edition

Step 6–Evaluate and Modify the Program

(cont’d.)

Figure 4-22 Command Prompt window

43

Page 152: c++Programming

• Fourth step in problem-solving process is coding the algorithm into a program

• C++ uses stream objects for standard input/output operations

• Use cin with extraction operator (>>) to get numeric or character data from the keyboard

• Use cout with insertion operator (<<) to display information on the screen

• The endl stream manipulator advances cursor to next line

An Introduction to Programming with C++, Seventh Edition

Summary

44

Page 153: c++Programming

• You do calculations by writing arithmetic expressions using arithmetic operators

• Each operator has a precedence: determines the order of evaluation in an expression

• Parentheses are used to override this order

• Compiler implicitly casts data types when possible, but you should explicitly cast to ensure correctness

• Use the static_cast operator to explicitly cast variables from one data type to another

An Introduction to Programming with C++, Seventh Edition

Summary (cont’d.)

45

Page 154: c++Programming

• An assignment statement assigns a value to a variable during runtime

• The expression on the right side of the assignment operator (=) in an assignment statement is stored in the variable on its left

• Fifth step of the problem-solving process is to desk-check the program using the same data used to desk-check the algorithm

• The sixth step is to evaluate and modify (if necessary) the program

An Introduction to Programming with C++, Seventh Edition

Summary (cont’d.)

46

Page 155: c++Programming

• Errors (called bugs) can either be syntax errors or logic errors

• You need a text editor and compiler to enter C++ instructions and compile them into a program

• C++ instructions are called source code and are saved in source files with the extension .cpp

• The compiler translates source code into machine code, also called object code

• A linker produces an executable file that contains all machine code necessary to run a C++ program

An Introduction to Programming with C++, Seventh Edition

Summary (cont’d.)

47

Page 156: c++Programming

• Programmers use comments to document a program internally

– Comments are not processed by the compiler

• The #include <filename> directive allows you to include multiple source files in a program

• The using namespace std; directive tells the compiler where definitions of standard C++ keywords and classes are in internal memory

• A namespace is a special area in the computer’s internal memory

An Introduction to Programming with C++, Seventh Edition

Summary (cont’d.)

48

Page 157: c++Programming

• Execution of every C++ program begins with the main() function

• The first line of a function is the function header

• The function body follows the header and is enclosed in braces

• Some functions return a data type; others return void

• Arithmetic assignment operators can be used to abbreviate certain assignment statements with arithmetic operators in them

An Introduction to Programming with C++, Seventh Edition

Summary (cont’d.)

49

Page 158: c++Programming

An Introduction to Programming with C++, Seventh Edition

Lab 4-1: Stop and Analyze

Figure 4-23 Examples for Lab 4-1

50

Page 159: c++Programming

• Plan and create an algorithm that displays the total amount a student owes for a semester

An Introduction to Programming with C++, Seventh Edition

Lab 4-2: Plan and Create

Figure 4-24 Problem specification for Lab 4-2

51

Page 160: c++Programming

• Modify the program in Lab 4-2 to account for Hoover College having courses that can be 0.5, 1, 2, or 3 semester hours

• Additionally, fee per hour is raised to $105

• Test the program twice, using 9.5 and 11 as the number of hours enrolled

An Introduction to Programming with C++, Seventh Edition

Lab 4-3: Modify

52

Page 161: c++Programming

• Desk-check the three lines of code shown in Figure 4-31

An Introduction to Programming with C++, Seventh Edition

Lab 4-4: Desk-Check

Figure 4-31 Code for Lab 4-4

53

Page 162: c++Programming

• Follow the instructions for starting C++ and opening the Lab4-5.cpp file

• If necessary, make the system(“pause”); statement a comment, and then save the program

• Run and then debug the program

An Introduction to Programming with C++, Seventh Edition

Lab 4-5: Debug

54

Page 163: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 5:

The Selection Structure

Page 164: c++Programming

• Include the selection structure in pseudocode and in a flowchart

• Code a selection structure using the if statement

• Include comparison operators in a selection structure’s condition

• Include logical operators in a selection structure’s condition

• Format numeric output

Objectives

An Introduction to Programming with C++, Seventh Edition 2

Page 165: c++Programming

• With only the sequence structure, all instructions are executed in order

• A selection structure is needed when a decision must be made (based on some condition) before selecting an instruction to execute

• A selection structure’s condition must be phrased as a Boolean expression (evaluates to true or false)

Making Decisions

An Introduction to Programming with C++, Seventh Edition 3

Page 166: c++Programming

• Single-alternative selection structure

– Set of instructions is executed only if condition evaluates to true

• Dual-alternative selection structure

– Executes different sets of instructions based on whether condition evaluates to true or false

• True path

– Instructions followed when condition evaluates to true

• False path

– Instructions followed when condition evaluates to false

Making Decisions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 4

Page 167: c++Programming

Making Decisions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 5

Figure 5-1 A problem that requires

the sequence structure only

Page 168: c++Programming

Making Decisions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 6

Figure 5-2 A problem that requires the sequence structure

and a single-alternative selection structure

Page 169: c++Programming

Making Decisions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 7

Figure 5-3 A problem that requires the sequence

structure and a dual-alternative selection structure

Page 170: c++Programming

• Recall from Chapter 2:

– Oval = start/stop symbol; rectangle = process symbol; parallelogram = input/output symbol

• Diamond symbol is called decision symbol

– Used to represent condition (decision) in selection and repetition structures

• Selection structures have one flowline leading in and two leading out

– “T” line leading out points to true path

– “F” line leading out points to false path

Flowcharting a Selection Structure

An Introduction to Programming with C++, Seventh Edition 8

Page 171: c++Programming

Flowcharting a Selection Structure

(cont’d)

An Introduction to Programming with C++, Seventh Edition 9

Figure 5-4 Flowchart showing a single-

alternative selection structure

Page 172: c++Programming

Flowcharting a Selection Structure

(cont’d)

An Introduction to Programming with C++, Seventh Edition 10

Figure 5-5 Flowchart showing a dual-alternative selection structure

Page 173: c++Programming

• The if (and else) statement is used to code most selection structures in C++

• Syntax

if (condition)

one or more statements (true path)

[else

one or more statements (false path)]

• Keyword if and condition are required

• Portion in brackets (else clause) is optional

– Only used for dual-alternative selection structures

Coding a Selection Structure in C++

An Introduction to Programming with C++, Seventh Edition 11

Page 174: c++Programming

• Programmer must supply condition and statements in true (and, optionally, false) path

• If path contains more than one statement, must be entered as a statement block (enclosed in {})

• Good programming practice to put comment at end of clause (example: //end if)

– Makes program easier to read and understand

• The condition must be a Boolean expression

– May contain variables, constants, arithmetic operators, comparison operators, and logical operators

Coding a Selection Structure in C++

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 12

Page 175: c++Programming

An Introduction to Programming with C++, Seventh Edition 13

Figure 5-6 How to use the if statement

Coding a Selection Structure in C++

(cont’d.)

Page 176: c++Programming

An Introduction to Programming with C++, Seventh Edition 14

Figure 5-6 How to use the if statement (cont’d)

Coding a Selection Structure in C++

(cont’d.)

Page 177: c++Programming

• Comparison operators are used to compare two values that have the same data type

– less than (<)

– less than or equal to (<=)

– greater than (>)

– greater than or equal to (>=)

– equal to (==)

– not equal to (!=)

• No spaces between dual-character symbols

Comparison Operators

An Introduction to Programming with C++, Seventh Edition 15

Page 178: c++Programming

• Have precedence numbers like arithmetic operators

• <, <=, >, and >= have precedence value 1

• == and != have precedence value 2

• Lower precedence evaluated first

• Equal precedence evaluated left to right

• Parentheses used to override precedence order

Comparison Operators (cont’d.)

An Introduction to Programming with C++, Seventh Edition 16

Page 179: c++Programming

• Expressions with comparison operators always evaluate to Boolean values

• Don’t confuse equality operator (==) with assignment operator (=)

• Don’t use equality (==) or inequality operator (!=) to compare real numbers

– Real numbers cannot be stored exactly

– Instead, test that absolute value of their difference is within some small threshold

Comparison Operators (cont’d.)

An Introduction to Programming with C++, Seventh Edition 17

Page 180: c++Programming

Comparison Operators (cont’d.)

An Introduction to Programming with C++, Seventh Edition 18

Figure 5-7 How to use comparison operators in an if statement’s condition

Page 181: c++Programming

Comparison Operators (cont’d.)

An Introduction to Programming with C++, Seventh Edition 19

Figure 5-8 Evaluation steps for an expression containing

arithmetic and comparison operators

Page 182: c++Programming

• Example program (next slide) takes in two integers, swaps them if first is greater, and then prints out lower number, followed by higher number

• Uses single-alternative selection structure with statement block in true path

• Creates temporary variable to accomplish swap

• Temp variable can only be used in statement block in which it is declared; called a local variable

Swapping Numeric Values

An Introduction to Programming with C++, Seventh Edition 20

Page 183: c++Programming

An Introduction to Programming with C++, Seventh Edition 21

Figure 5-9 IPO chart information and C++

instructions for the swapping program

Swapping Numeric Values (cont’d.)

Page 184: c++Programming

Swapping Numeric Values (cont’d.)

An Introduction to Programming with C++, Seventh Edition 22

Figure 5-10 Illustration of the swapping concept

Page 185: c++Programming

Swapping Numeric Values (cont’d.)

An Introduction to Programming with C++, Seventh Edition 23

Figure 5-11 Flowchart for the swapping program

Page 186: c++Programming

Swapping Numeric Values (cont’d.)

An Introduction to Programming with C++, Seventh Edition 24

Figure 5-12 Sample run of the swapping program

Page 187: c++Programming

• Example program (next slide) displays the sum or difference of two numbers entered by the user

• Choice of addition or subtraction is entered by user as well

• Uses a dual-alternative selection structure

Displaying the Sum or Difference

An Introduction to Programming with C++, Seventh Edition 25

Page 188: c++Programming

Displaying the Sum or Difference

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 26

Figure 5-13 IPO chart information and C++

instructions for the sum or difference program

Page 189: c++Programming

An Introduction to Programming with C++, Seventh Edition 27

Figure 5-14 Flowchart for sum or difference program

Displaying the Sum or Difference

(cont’d.)

Page 190: c++Programming

An Introduction to Programming with C++, Seventh Edition 28

Figure 5-15 Sample run of the sum or difference program

Displaying the Sum or Difference

(cont’d.)

Page 191: c++Programming

• Logical operators allow you to combine two or more conditions (sub-conditions) into one compound condition

• Also called as Boolean operators (always evaluate to true or false)

• Two most common are And (&&) and Or (||)

• All sub-conditions must be true for a compound condition using And to be true

• Only one of the sub-conditions must be true for a compound condition using Or to be true

Logical Operators

An Introduction to Programming with C++, Seventh Edition 29

Page 192: c++Programming

• And evaluated before Or in an expression

• Logical operators evaluated after arithmetic and comparison operators

• Parentheses can override precedence ordering

• Truth tables summarize how computer evaluates logical operators

• Only necessary sub-conditions are evaluated; called short-circuit evaluation

– Example: if first sub-condition in an And clause is false, second sub-condition need not be evaluated

Logical Operators (cont’d.)

An Introduction to Programming with C++, Seventh Edition 30

Page 193: c++Programming

Logical Operators (cont’d.)

An Introduction to Programming with C++, Seventh Edition 31

Figure 5-16 How to use logical operators in an if statement’s condition

Page 194: c++Programming

Logical Operators (cont’d.)

An Introduction to Programming with C++, Seventh Edition 32

Figure 5-16 How to use logical operators in an if statement’s condition (cont’d)

Page 195: c++Programming

Logical Operators (cont’d.)

An Introduction to Programming with C++, Seventh Edition 33

Figure 5-17 Truth tables for the logical operators

Page 196: c++Programming

• Two example problem descriptions are given, and truth tables for And and Or operators are used to find appropriate sub-conditions and logical operators

• Calculate bonus for A-rated salespeople with monthly sales greater than $5000

rating == ‘A’ && sales > 5000

• Send letter to all A-rated and B-rated salespeople

rating == ‘A’ || rating == ‘B’

Using the Truth Tables

An Introduction to Programming with C++, Seventh Edition 34

Page 197: c++Programming

• Example problem description is given in which the gross pay of an employee must be calculated

• Program must verify that number of hours worked is between 0 and 40

• Process of verifying that input data is within expected range is known as data validation

• Program outputs gross pay if the number of hours worked is valid and is an error message otherwise

Calculating Gross Pay

An Introduction to Programming with C++, Seventh Edition 35

Page 198: c++Programming

Calculating Gross Pay (cont’d.)

An Introduction to Programming with C++, Seventh Edition 36

Figure 5-18 Examples of C++

instructions for the gross pay program

Page 199: c++Programming

Calculating Gross Pay (cont’d.)

An Introduction to Programming with C++, Seventh Edition 37

Figure 5-19 First sample run of

the gross pay program’s code

Figure 5-20 Second sample run of

the gross pay program’s code

Page 200: c++Programming

• Example problem description is given in which program must output “Pass” if user enters ‘P’ or ‘p’, and “Fail” otherwise

• Character comparisons are case sensitive in C++

• Program must check separately whether the user entered ‘P’ or ‘p’

• Dual-alternative selection structure is used to implement program

• Compound condition with Or operator is used to perform check

Pass/Fail Program

An Introduction to Programming with C++, Seventh Edition 38

Page 201: c++Programming

An Introduction to Programming with C++, Seventh Edition 39

Figure 5-21 Examples of C++ instructions for the Pass/Fail program

Pass/Fail Program (cont’d)

Page 202: c++Programming

Pass/Fail Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 40

Figure 5-22 First sample run of

the Pass/Fail program’s code

Figure 5-23 Second sample run of

the Pass/Fail program’s code

Page 203: c++Programming

An Introduction to Programming with C++, Seventh Edition 41

Figure 5-24 Listing and an example of

arithmetic, comparison, and logical operators

Summary of Operators

Page 204: c++Programming

• toupper and tolower functions used to convert characters between uppercase and lowercase

• toupper function temporarily converts a character to uppercase; tolower function temporarily converts a character to lowercase

• Syntax is toupper(charVariable) and tolower(charVariable)

• Item between parentheses in a function’s syntax is called an argument – information the function needs to perform its task

Converting a Character to Uppercase

or Lowercase

An Introduction to Programming with C++, Seventh Edition 42

Page 205: c++Programming

• Each function copies the character in its argument to a temporary location in internal memory, converts the character to the appropriate case, and returns the temporary character

• Neither function changes the contents of its argument, but rather, changes the temporary variable

Converting a Character to Uppercase

or Lowercase (cont’d.)

An Introduction to Programming with C++, Seventh Edition 43

Page 206: c++Programming

An Introduction to Programming with C++, Seventh Edition 44

Figure 5-25 How to use the toupper and tolower functions

Converting a Character to Uppercase

or Lowercase (cont’d.)

Page 207: c++Programming

• Real numbers are displayed in either fixed-point or scientific (e) notation

• Small real numbers (six or less digits before decimal place) displayed in fixed-point notation

– Example: 1,234.56 displayed as 1234.560000

• Large real numbers (more than six digits before decimal place) displayed in e notation

– Example: 1,225,000.00 displayed as 1.225e+006

• Purpose of program determines appropriate format

Formatting Numeric Output

An Introduction to Programming with C++, Seventh Edition 45

Page 208: c++Programming

• Stream manipulators allow control over formatting

• fixed stream manipulator displays real numbers in fixed-point notation

• scientific stream manipulator displays real numbers in e notation

• Stream manipulator must appear in a cout statement before numbers you want formatted

• Manipulator can appear by itself in a cout statement or can be included with other information

Formatting Numeric Output (cont’d.)

An Introduction to Programming with C++, Seventh Edition 46

Page 209: c++Programming

• Manipulator remains in effect until end of program execution or until another manipulator is processed

• Numbers formatted with fixed stream manipulator always have six numbers to the right of the decimal place

– Number is padded with zeros if there aren’t six digits

• Example: 123.456 is displayed as 123.456000

– Number is rounded and truncated if there are more than six digits

• Example: 123.3456789 is displayed as 123.345679

Formatting Numeric Output (cont’d.)

An Introduction to Programming with C++, Seventh Edition 47

Page 210: c++Programming

• setprecision stream manipulator controls number of decimal places

• Syntax setprecision(numberOfDecimalPlaces)

• You can include setprecision and fixed manipulators in the same cout statement

• Definition of setprecision manipulator contained in iomanip file

• Program must contain #include <iomanip> directive to use setprecision manipulator

Formatting Numeric Output (cont’d.)

An Introduction to Programming with C++, Seventh Edition 48

Page 211: c++Programming

Formatting Numeric Output (cont’d.)

An Introduction to Programming with C++, Seventh Edition 49

Figure 5-26 How to use the fixed

and scientific stream manipulators

Page 212: c++Programming

Formatting Numeric Output (cont’d.)

An Introduction to Programming with C++, Seventh Edition 50

Figure 5-27 How to use the setprecision stream manipulator

Page 213: c++Programming

• Selection structure used when you want a program to make a decision before choosing next instruction

• Selection structure’s condition must evaluate to true or false

• In single-alternative and dual-alternative selection structures, the instructions followed when the condition is true are placed in the true path

• In dual-alternative selection structures, the instructions followed when the condition is false are placed in the false path

Summary

An Introduction to Programming with C++, Seventh Edition 51

Page 214: c++Programming

• A diamond (decision symbol) is used to represent a selection structure’s condition in a flowchart

• Each selection structure has one flowline going into the diamond and two coming out (“T” line represents the true path, and “F” line the false path)

• The if statement is used to code most selection structures

• True or false paths with more than one statement must be entered as a statement block (enclosed in {})

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 52

Page 215: c++Programming

• Good practice to end if and else statements with a comment (//end if)

• Comparison operators are used to compare values – Expressions using them evaluate to true or false

• Comparison operators have precedence ordering similar to arithmetic operators

• Don’t use == and != to compare real numbers

• Local variables can only be used in the statement block in which they are declared

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 53

Page 216: c++Programming

• Expressions with logical operators evaluate to true or false

• And (&&) and Or (||) are logical operators, which also have precedence

• Arithmetic operators are evaluated first in an expression, followed by comparison operators and then logical operators

• Character comparisons are case sensitive

• toupper and tolower functions temporarily convert a character to upper or lowercase

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 54

Page 217: c++Programming

• The fixed and scientific stream manipulators allow you to format real numbers

• The setprecision manipulator allows you to specify the number of decimal places that appear

• fixed and scientific are defined in the iostream file

• setprecision is defined in the iomanip file

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 55

Page 218: c++Programming

Lab 5-1: Stop and Analyze

An Introduction to Programming with C++, Seventh Edition 56

Figure 5-28 Program for Lab 5-1

Page 219: c++Programming

• Plan and create an algorithm for the manager of the Willow Springs Health Club

Lab 5-2: Plan and Create

An Introduction to Programming with C++, Seventh Edition 57

Figure 5-29 Problem specification for Lab 5-2

Page 220: c++Programming

• Currently, the if statement’s true path in Lab 5-2 handles valid data, while its false path handles invalid data

• Modify the program so that invalid data is handled in the true path, and valid data is handled in the false path

Lab 5-3: Modify

An Introduction to Programming with C++, Seventh Edition 58

Page 221: c++Programming

• Desk-check the code shown in Figure 5-34 using the letter ‘P’

• Why is it inefficient? How could you improve it?

Lab 5-4: Desk-Check

An Introduction to Programming with C++, Seventh Edition 59

Figure 5-35 Code for Lab 5-4

Page 222: c++Programming

• Follow the instructions for starting C++ and opening the Lab5-5.cpp file

• Test the program using codes 1, 2, and 3

• Debug the program

Lab 5-5: Debug

An Introduction to Programming with C++, Seventh Edition 60

Page 223: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 6:

More on the Selection Structure

Page 224: c++Programming

• Include a nested selection structure in pseudocode and in a flowchart

• Code a nested selection structure

• Recognize common logic errors in selection structures

• Include a multiple-alternative selection structure in pseudocode and in a flowchart

• Code a multiple-alternative selection structure in C++

Objectives

An Introduction to Programming with C++, Seventh Edition 2

Page 225: c++Programming

• True and false paths of a selection structure can contain other selection structures

• Inner selection structures are referred to as nested selection structures; contained (nested) within an outer selection structure

• Nested selection structures are used when more than one decision needs to be made before choosing an instruction

• Inner (nested) selection structures are indented within their outer selection structures

Making Decisions

An Introduction to Programming with C++, Seventh Edition 3

Page 226: c++Programming

An Introduction to Programming with C++, Seventh Edition 4

Figure 6-1 Problem that requires a selection structure

Making Decisions (cont’d.)

Page 227: c++Programming

Making Decisions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 5

Figure 6-2 Problem that requires a nested selection structure

Page 228: c++Programming

Making Decisions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 6

Figure 6-3 Problem that requires two nested selection structures

Page 229: c++Programming

• Outer and inner selection structures can be thought of as making primary and secondary decisions, respectively

• Secondary decision is called such because whether it needs to be made depends on the result of a primary decision

Flowcharting a Nested Selection

Structure

An Introduction to Programming with C++, Seventh Edition 7

Page 230: c++Programming

Flowcharting a Nested Selection

Structure (cont’d.)

An Introduction to Programming with C++, Seventh Edition 8

Figure 6-6 Problem specification for voter eligibility problem

Page 231: c++Programming

An Introduction to Programming with C++, Seventh Edition 9

Figure 6-6 A correct solution to the voter eligibility problem

Flowcharting a Nested Selection

Structure (cont’d.)

Page 232: c++Programming

An Introduction to Programming with C++, Seventh Edition 10

Figure 6-7 Another correct solution to the voter eligibility problem

Flowcharting a Nested Selection

Structure (cont’d.)

Page 233: c++Programming

• Code for nested selection structures uses the if and else statements

• Nested selection structures can be placed in either if or else statement blocks

• Correct tabbing makes code easier to read

Coding a Nested Selection Structure

An Introduction to Programming with C++, Seventh Edition 11

Page 234: c++Programming

Coding a Nested Selection Structure

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 12

Figure 6-8 Modified problem specification for the

health club problem from Chapter 5’s Lab 5-2

Page 235: c++Programming

An Introduction to Programming with C++, Seventh Edition 13

Figure 6-8 Modified problem specification for the

health club problem from Chapter 5’s Lab 5-2 (cont’d)

Coding a Nested Selection Structure

(cont’d.)

Page 236: c++Programming

An Introduction to Programming with C++, Seventh Edition 14

Figure 6-9 Sample run of the modified health club program

Coding a Nested Selection Structure

(cont’d.)

Page 237: c++Programming

An Introduction to Programming with C++, Seventh Edition 15

Figure 6-10 Flowchart for the modified health club program

Coding a Nested Selection Structure

(cont’d.)

Page 238: c++Programming

• Three common logic errors made when writing selection structures

– Using a compound condition rather than a nested selection structure

– Reversing the outer and nested decisions

– Using an unnecessary nested selection structure

Logic Errors in Selection Structures

An Introduction to Programming with C++, Seventh Edition 16

Page 239: c++Programming

Logic Errors in Selection Structures

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 17

Figure 6-11 A correct algorithm for the bonus problem

Page 240: c++Programming

An Introduction to Programming with C++, Seventh Edition 18

Figure 6-12 Test data and manually calculated results

Figure 6-13 Current status of the desk-check table

Figure 6-14 Desk-check table after completing the first desk-check

Logic Errors in Selection Structures

(cont’d.)

Page 241: c++Programming

An Introduction to Programming with C++, Seventh Edition 19

Figure 6-16 Desk-check table after completing the third desk-check

Figure 6-15 Desk-check table after completing the second desk-check

Logic Errors in Selection Structures

(cont’d.)

Page 242: c++Programming

• Using a compound condition rather than a nested selection structure

• Ignores the hierarchy between two sub-conditions – One applies only if the other is a certain value

First Logic Error

An Introduction to Programming with C++, Seventh Edition 20

Page 243: c++Programming

First Logic Error (cont’d.)

An Introduction to Programming with C++, Seventh Edition 21

Figure 6-17 Correct algorithm and incorrect algorithm containing the first logic error

Page 244: c++Programming

An Introduction to Programming with C++, Seventh Edition 22

Figure 6-18 Desk-check table for the incorrect algorithm in Figure 6-17

First Logic Error (cont’d.)

Page 245: c++Programming

Second Logic Error

An Introduction to Programming with C++, Seventh Edition 23

Figure 6-19 Correct algorithm and an incorrect

algorithm containing the second logic error

• Reversing outer and nested selection structures

Page 246: c++Programming

Second Logic Error (cont’d.)

An Introduction to Programming with C++, Seventh Edition 24

Figure 6-20 Desk-check table for the incorrect algorithm in Figure 6-19

Page 247: c++Programming

• Using an unnecessary nested selection structure

• Often will produce the correct result, but will be inefficient

Third Logic Error

An Introduction to Programming with C++, Seventh Edition 25

Page 248: c++Programming

Third Logic Error (cont’d.)

An Introduction to Programming with C++, Seventh Edition 26

Figure 6-21 Correct algorithm and an incorrect

algorithm containing the third logic error

Page 249: c++Programming

Third Logic Error (cont’d.)

An Introduction to Programming with C++, Seventh Edition 27

Figure 6-22 Desk-check table for inefficient algorithm in Figure 6-21

Page 250: c++Programming

• Sometimes problems require a selection structure that chooses between several alternatives

• Called multiple-alternative selection structures or extended selection structures

• In a flowchart, diamond symbol is used; has multiple flowlines leading out, not just two

• Each flowline represents a possible path, marked with the value that represents that path

• if/else statements can be used to implement it; uses multiple if else clauses

Multiple-Alternative Selection

Structures

An Introduction to Programming with C++, Seventh Edition 28

Page 251: c++Programming

Multiple-Alternative Selection

Structures (cont’d.)

An Introduction to Programming with C++, Seventh Edition 29

Figure 6-25 Problem specification for Kindlon High School problem

Page 252: c++Programming

Multiple-Alternative Selection

Structures (cont’d.)

An Introduction to Programming with C++, Seventh Edition 30

Figure 6-25 IPO chart for the Kindlon High School problem

Page 253: c++Programming

Multiple-Alternative Selection

Structures (cont’d.)

An Introduction to Programming with C++, Seventh Edition 31

Figure 6-26 Flowchart for the Kindlon High School problem

Page 254: c++Programming

An Introduction to Programming with C++, Seventh Edition 32

Figure 6-27 Two ways of coding the multiple-alternative

selection structure from Figures 6-25 and 6-26

Multiple-Alternative Selection

Structures (cont’d.)

Page 255: c++Programming

• Can sometimes use the switch statement to code a multiple-alternative selection structure

• Statement begins with switch keyword followed by a selector expression in parentheses

• Selector expression can contain any combination of variables, constants, functions, and operators

• Must result in a data type that is bool, char, short, int, or long

• Between opening and closing braces (after selector expression), there are one or more case clauses

The switch Statement

An Introduction to Programming with C++, Seventh Edition 33

Page 256: c++Programming

• Each case clause represents a different alternative and contains a value followed by a colon

• Can include as many case clauses as necessary

• Value for each case clause can be a literal constant, named constant, or an expression composed of literal and named constants

• Data type of the value should be the same data type as the selector expression

The switch Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 34

Page 257: c++Programming

• Each case clause contains one or more statements processed when selector expression matches that case’s value

• break statement tells computer to break out of switch at that point; must be the last statement of a case clause

• Without a break statement, computer continues to process instructions in later case clauses

• After processing break, computer processes next instruction after switch statement’s closing brace

The switch Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 35

Page 258: c++Programming

• Good programming practice to document end of switch with a comment (//end switch)

• Can also include one default clause; processed if selector expression does not match any values in case clauses

• default clause can appear anywhere, but usually entered as last clause

– If it is the last clause, a break statement is not needed at its end

– Otherwise, a break statement is needed to prevent computer from processing later case clauses

The switch Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 36

Page 259: c++Programming

The switch Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 37

Figure 6-28 How to use the switch statement

Page 260: c++Programming

An Introduction to Programming with C++, Seventh Edition 38

Example similar to code in Figure 6-28

The switch Statement (cont’d.)

Page 261: c++Programming

The switch Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 39

Figure 6-29 Problem specification for the Warren Company problem

Page 262: c++Programming

An Introduction to Programming with C++, Seventh Edition 40

Figure 6-29 IPO chart and C++ instructions for the Warren Company problem

The switch Statement (cont’d.)

Page 263: c++Programming

The switch Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 41

Figure 6-30 Flowchart for the Warren Company problem

Page 264: c++Programming

• Can nest a selection structure within true or false path of another selection structure

• Three common logic errors when writing selection structures

– Using a compound condition instead of a nested selection structure

– Reversing the inner and outer selection structures

– Using an unnecessary nested selection structure

Summary

An Introduction to Programming with C++, Seventh Edition 42

Page 265: c++Programming

• Some solutions require selection structures that choose from multiple alternatives; called multiple-alternative or extended selection structures

• Can code these either with if/else statements or the switch statement

• Diamond is used to represent multiple-alternative selection structures in a flowchart

• Has multiple flowlines leading out; each representing a possible path and marked with appropriate values

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 43

Page 266: c++Programming

• In a switch statement, the data type of the value in each case clause must be compatible with data type of selector expression

• Selector expression must evaluate to value of type bool, char, short, int, or long

• Most case clauses contain a break statement; tells the computer to leave the switch statement

• Good practice to mark end of switch statement with a comment (//end switch)

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 44

Page 267: c++Programming

An Introduction to Programming with C++, Seventh Edition 45

Figure 6-31 Flowchart for Lab 6-1

Lab 6-1: Stop and Analyze

Page 268: c++Programming

Lab 6-2: Plan and Create

An Introduction to Programming with C++, Seventh Edition 46

Figure 6-32 Problem specification and

calculation examples for Lab 6-2

Page 269: c++Programming

• Modify the program in Lab 6-2 to calculate commission based on information in Figure 6-38

• If the sales are less than zero, display “The sales cannot be less than zero.”

• If the code is not 1, 2, or 3, display “Invalid Code”

Lab 6-3: Modify

An Introduction to Programming with C++, Seventh Edition 47

Figure 6-38 Problem specification for Lab 6-3

Page 270: c++Programming

An Introduction to Programming with C++, Seventh Edition 48

Figure 6-39 Code for Lab 6-4

Lab 6-4: Desk-Check

Page 271: c++Programming

• Follow the instructions for starting C++ and opening the Lab6-5.cpp file

• Test the program using codes 1, 2, 3, 4, 5, 9, and -3

• Debug the program

Lab 6-5: Debug

An Introduction to Programming with C++, Seventh Edition 49

Page 272: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 7:

The Repetition Structure

Page 273: c++Programming

• Differentiate between a pretest loop and a posttest loop

• Include a pretest loop in pseudocode

• Include a pretest loop in a flowchart

• Code a pretest loop using the C++ while statement

• Utilize counter and accumulator variables

• Code a pretest loop using the C++ for statement

Objectives

An Introduction to Programming with C++, Seventh Edition 2

Page 274: c++Programming

• The repetition structure, or loop, processes one or more instructions repeatedly

• Every loop contains a Boolean condition that controls whether the instructions are repeated

• A looping condition says whether to continue looping through instructions

• A loop exit condition says whether to stop looping through the instructions

• Every looping condition can be expressed as a loop exit condition (its opposite)

Repeating Program Instructions

An Introduction to Programming with C++, Seventh Edition 3

Page 275: c++Programming

• C++ uses looping conditions in repetition structures

• A repetition structure can be pretest or posttest

• In a pretest loop, the condition is evaluated before the instructions in the loop are processed

• In a posttest loop, the condition is evaluated after the instructions in the loop are processed

• In both cases, the condition is evaluated with each repetition

Repeating Program Instructions

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 4

Page 276: c++Programming

• The instructions in a posttest loop will always be processed at least once

• Instructions in a pretest loop may not be processed if the condition initially evaluates to false

• The repeatable instructions in a loop are called the loop body

• The condition in a loop must evaluate to a Boolean value

Repeating Program Instructions

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 5

Page 277: c++Programming

Repeating Program Instructions

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 6

Figure 7-1 A problem that requires the sequence

and selection structures

Page 278: c++Programming

Repeating Program Instructions

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 7

Figure 7-2 A problem that requires the

sequence and repetition structures

Page 279: c++Programming

• Most loops have a condition and a loop body

• Some loops require the user to enter a special sentinel value to end the loop

• Sentinel values should be easily distinguishable from the valid data recognized by the program

• When a loop’s condition evaluates to true, the instructions in the loop body are processed

• Otherwise, the instructions are skipped and processing continues with the first instruction after the loop

Using a Pretest Loop to Solve a Real-

World Problem

An Introduction to Programming with C++, Seventh Edition 8

Page 280: c++Programming

• After each processing of the loop body (iteration), the loop’s condition is reevaluated to determine if the instructions should be processed again

• A priming read is an instruction that appears before a loop and is used to set up the loop with an initial value entered by the user

• An update read is an instruction that appears within a loop that allows the user to enter a new value at each iteration of the loop

Using a Pretest Loop to Solve a Real-

World Problem (cont.)

An Introduction to Programming with C++, Seventh Edition 9

Page 281: c++Programming

Using a Pretest Loop to Solve a Real-

World Problem (cont’d.)

An Introduction to Programming with C++, Seventh Edition 10

Figure 7-4 Problem specification and IPO chart

for the Totally Sweet Shoppe program

Page 282: c++Programming

An Introduction to Programming with C++, Seventh Edition 11

Figure 7-5 Problem specification and IPO chart for the Wheels & More program

Using a Pretest Loop to Solve a Real-

World Problem (cont’d.)

Page 283: c++Programming

Using a Pretest Loop to Solve a Real-

World Problem (cont’d.)

An Introduction to Programming with C++, Seventh Edition 12

Figure 7-6 Components of the Wheels & More algorithm

Page 284: c++Programming

• The diamond symbol in a flowchart is the decision symbol – represents repetition structures

• A diamond representing a repetition structure contains a Boolean condition

• The condition determines whether the instructions in the loop are processed

• A diamond representing a repetition structure has one flowline leading into it and two leading out

Flowcharting a Pretest Loop

An Introduction to Programming with C++, Seventh Edition 13

Page 285: c++Programming

• The flowlines leading out are marked “T” (true) and “F” (false)

• The “T” line points to the loop body

• The “F” line points to the instructions to be processed if the loop’s condition evaluates to false

• The flowline entering the diamond and symbols and flowlines of the true path form a circle, or loop

• This distinguishes a repetition structure from a selection structure in a flowchart

Flowcharting a Pretest Loop (cont’d.)

An Introduction to Programming with C++, Seventh Edition 14

Page 286: c++Programming

Flowcharting a Pretest Loop (cont’d.)

An Introduction to Programming with C++, Seventh Edition 15

Figure 7-7 Wheels & More algorithm shown in flowchart form

Page 287: c++Programming

Flowcharting a Pretest Loop (cont’d.)

An Introduction to Programming with C++, Seventh Edition 16

Figure 7-8 Input and output items entered in the desk-check table

Figure 7-9 First hours worked entry in the desk-check table

Figure 7-10 First employee’s information recorded in the desk-check table

Page 288: c++Programming

Flowcharting a Pretest Loop (cont’d.)

An Introduction to Programming with C++, Seventh Edition 17

Figure 7-11 Second employee’s information recorded in the desk-check table

Figure 7-12 Completed desk-check table

Page 289: c++Programming

• You can use the while statement to code a pretest loop in C++

• Syntax is:

while (condition)

one statement or a statement block to be processed as long as the condition is true

• Must supply looping condition (Boolean expression)

• condition can contain constants, variables, functions, arithmetic operators, comparison operators, and logical operators

The while Statement

An Introduction to Programming with C++, Seventh Edition 18

Page 290: c++Programming

• Must also provide loop body statements, which are processed repeatedly as long as condition is true

• If more than one statement in loop body, must be entered as a statement block (enclosed in braces)

• Can include braces even if there is only one statement in the statement block

• Good programming practice to include a comment, such as //end while, to mark the end of the while statement

The while Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 19

Page 291: c++Programming

• A loop whose instructions are processed indefinitely is called an infinite loop or endless loop

• You can usually stop a program that has entered an infinite loop by pressing Ctrl+c

The while Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 20

Page 292: c++Programming

An Introduction to Programming with C++, Seventh Edition 21

Figure 7-13 How to use the while statement

The while Statement (cont’d.)

Page 293: c++Programming

An Introduction to Programming with C++, Seventh Edition 22

An alternate example using the while statement

The while Statement (cont’d.)

Page 294: c++Programming

An Introduction to Programming with C++, Seventh Edition 23

Figure 7-14 IPO chart information and C++

instructions for the Wheels & More program

The while Statement (cont’d.)

Page 295: c++Programming

The while Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 24

Figure 7-15 A sample run of the

Wheels & More program

Page 296: c++Programming

• Some problems require you to calculate a total or average

• To do this, you use a counter, accumulator, or both

• A counter is a numeric variable used for counting something

• An accumulator is a numeric variable used for accumulating (adding together) multiple values

• Two tasks are associated with counters and accumulators: initializing and updating

Using Counters and Accumulators

An Introduction to Programming with C++, Seventh Edition 25

Page 297: c++Programming

• Initializing means assigning a beginning value to a counter or accumulator (usually 0) – happens once, before the loop is processed

• Updating (or incrementing) means adding a number to the value of a counter or accumulator

• A counter is updated by a constant value (usually 1)

• An accumulator is updated by a value that varies

• Update statements are placed in the body of a loop since they must be performed at each iteration

Using Counters and Accumulators

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 26

Page 298: c++Programming

• Example problem and program solution (following slides)

– Program takes in a sequence of sales amounts from the keyboard and outputs their average

– Uses a counter to keep track of the number of sales entered and an accumulator to keep track of the total sales

– Both are initialized to 0

– The loop ends when the user enters a sentinel value (-1)

The Sales Express Program

An Introduction to Programming with C++, Seventh Edition 27

Page 299: c++Programming

The Sales Express Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 28

Figure 7-17 Problem specification for the Sales Express program

Page 300: c++Programming

An Introduction to Programming with C++, Seventh Edition 29

Figure 7-17 IPO chart information and C++

instructions for the Sales Express program

The Sales Express Program (cont’d.)

Page 301: c++Programming

The Sales Express Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 30

Figure 7-17 IPO chart information and C++

instructions for the Sales Express program (cont’d)

Page 302: c++Programming

The Sales Express Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 31

Figure 7-18 Flowchart for the Sales Express program

Page 303: c++Programming

The Sales Express Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 32

Figure 7-19 Desk-check table after the first sales amount is entered

Figure 7-20 Desk-check showing the first update

to the counter and accumulator variables

Page 304: c++Programming

The Sales Express Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 33

Figure 7-21 Desk-check table after the second update

to the counter and accumulator variables

Figure 7-22 Completed desk-check for the Sales Express program

Page 305: c++Programming

The Sales Express Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 34

Figure 7-23 First sample run of the Sales Express program

Figure 7-24 Second sample run of the Sales Express program

Page 306: c++Programming

• Loops can be controlled using a counter rather than a sentinel value

• These are called counter-controlled loops

• Example problem and program solution (following slides)

– Counter-controlled loop is used that totals the quarterly sales from three regions

– Loop repeats three times, once for each region, using a counter to keep track

Counter-Controlled Pretest Loops

An Introduction to Programming with C++, Seventh Edition 35

Page 307: c++Programming

Counter-Controlled Pretest Loops

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 36

Figure 7-25 Problem specification for the Jasper Music Company program

Page 308: c++Programming

An Introduction to Programming with C++, Seventh Edition 37

Figure 7-25 IPO chart information and C++

instructions for the Jasper Music Company program

Counter-Controlled Pretest Loops

(cont’d.)

Page 309: c++Programming

An Introduction to Programming with C++, Seventh Edition 38

Figure 7-26 Flowchart for the Jasper Music Company program

Counter-Controlled Pretest Loops

(cont’d.)

Page 310: c++Programming

An Introduction to Programming with C++, Seventh Edition 39

Figure 7-27 Desk-check table after the variable

declaration statements are processed

Figure 7-28 Results of processing loop body instructions first time

Figure 7-29 Results of processing loop body instructions second time

Counter-Controlled Pretest Loops

(cont’d.)

Page 311: c++Programming

An Introduction to Programming with C++, Seventh Edition 40

Figure 7-31 Sample run of Jasper Music Company program

Figure 7-30 Results of processing loop body instructions third time

Counter-Controlled Pretest Loops

(cont’d.)

Page 312: c++Programming

• The for statement can also be used to code any pretest loop in C++

• Commonly used to code counter-controlled pretest loops (more compact than while in this case)

• Syntax:

for ([initialization]; condition; [update])

one statement or a statement block to be

processed as long as condition is true

• initialization and update arguments are optional

The for Statement

An Introduction to Programming with C++, Seventh Edition 41

Page 313: c++Programming

• initialization argument usually creates and initializes a counter variable

• Counter variable is local to for statement (can only be used inside the loop)

• condition argument specifies condition that must be true for the loop body to be processed

• condition must be a Boolean expression

– May contain variables, constants, functions, arithmetic operators, comparison operators, and logical operators

The for Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 42

Page 314: c++Programming

• Loop ends when condition evaluates to false

• update argument usually contains an expression that updates the counter variable

• Loop body follows the for clause

– Must be placed in braces if it contains more than one statement

– Braces can be used even if the loop body contains only one statement

• Good programming practice to place a comment, such as //end for, to mark the end of a for loop

The for Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 43

Page 315: c++Programming

The for Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 44

Figure 7-32 How to use the for statement

Page 316: c++Programming

An Introduction to Programming with C++, Seventh Edition 45

Figure 7-33 Processing steps for the code

shown in Example 1 in Figure 7-32

The for Statement (cont’d.)

Page 317: c++Programming

• Extended example of a problem and program solution (following slides)

– Program totals up the sales from three stores using a for loop

The Holmes Supply Program

An Introduction to Programming with C++, Seventh Edition 46

Figure 7-34 Problem specification for the

Holmes Supply Company program

Page 318: c++Programming

An Introduction to Programming with C++, Seventh Edition 47

Figure 7-34 IPO chart information and C++

instructions for the Holmes Supply Company program

The Holmes Supply Program (cont’d.)

Page 319: c++Programming

The Holmes Supply Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 48

Figure 7-35 Results of processing the declaration

statements and initialization argument

Figure 7-36 Desk-check table after update argument is processed first time

Figure 7-37 Desk-check table after update argument is processed second time

Page 320: c++Programming

The Holmes Supply Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 49

Figure 7-38 Desk-check table after update argument is processed third time

Figure 7-39 Sample run of Holmes Supply Company program

Page 321: c++Programming

• Extended example of a problem and program solution (following slides)

– Calculates the commission for a given sales amount using four different rates

– A for loop keeps track of each of the four rates

The Colfax Sales Program

An Introduction to Programming with C++, Seventh Edition 50

Figure 7-40 Problem specification for the Colfax Sales program

Page 322: c++Programming

An Introduction to Programming with C++, Seventh Edition 51

Figure 7-40 IPO chart information and C++

instructions for the Colfax Sales program

The Colfax Sales Program (cont’d.)

Page 323: c++Programming

The Colfax Sales Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 52

Figure 7-41 Processing steps for the code in Figure 7-40

Page 324: c++Programming

The Colfax Sales Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 53

Figure 7-41 Processing steps for the code in Figure 7-40 (cont’d.)

Page 325: c++Programming

The Colfax Sales Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 54

Figure 7-42 A sample run of the Colfax Sales program

Page 326: c++Programming

The Colfax Sales Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 55

Figure 7-43 Colfax Sales algorithm shown in flowchart form

Page 327: c++Programming

• Alternative version of the Wheels & More program (following slides)

– Uses a for loop instead of a while loop

Another Version of the Wheels &

More Program

An Introduction to Programming with C++, Seventh Edition 56

Page 328: c++Programming

An Introduction to Programming with C++, Seventh Edition 57

Figure 7-44 IPO chart information and modified

C++ instructions for the Wheels & More program

Another Version of the Wheels &

More Program (cont’d.)

Page 329: c++Programming

An Introduction to Programming with C++, Seventh Edition 58

Figure 7-45 Processing steps for the code shown in Figure 7-44

Another Version of the Wheels &

More Program (cont’d.)

Page 330: c++Programming

• Use the repetition structure (or loop) to repeatedly process one or more instructions

• Loop repeats as long as looping condition is true (or until loop exit condition has been met)

• A repetition structure can be pretest or posttest

• In a pretest loop, the loop condition is evaluated before instructions in loop body are processed

• In a posttest loop, the evaluation occurs after instructions in loop body are processed

Summary

An Introduction to Programming with C++, Seventh Edition 59

Page 331: c++Programming

• Condition appears at the beginning of a pretest loop – must be a Boolean expression

• If condition evaluates to true, the instructions in the loop body are processed; otherwise, the loop body instructions are skipped

• Some loops require the user to enter a special sentinel value to end the loop

• Sentinel values should be easily distinguishable from valid data recognized by the program

• Other loops are terminated by using a counter

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 60

Page 332: c++Programming

• Input instruction that appears above a pretest loop’s condition is the priming read

– Sets up the loop by getting first value from user

• Input instruction that appears within the loop is the update read

– Gets the remaining values (if any) from user

• In most flowcharts, diamond (decision symbol) is used to represent a repetition structure’s condition

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 61

Page 333: c++Programming

• Counters and accumulators are used in repetition structures to calculate totals and averages

• All counters and accumulators must be initialized and updated

• Counters are updated by a constant value

• Accumulators are updated by a variable amount

• You can use either the while statement or the for statement to code a pretest loop in C++

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 62

Page 334: c++Programming

• Study the program in Figure 7-46 and answer the questions

• The program calculates the average outside temperature

Lab 7-1: Stop and Analyze

An Introduction to Programming with C++, Seventh Edition 63

Page 335: c++Programming

Lab 7-2: Plan and Create

An Introduction to Programming with C++, Seventh Edition 64

Figure 7-47 Problem specification for Lab 7-2

Page 336: c++Programming

• Modify the program in Lab 7-2 to display the total number of scores entered

• Test the program using scores 45, 40, 41, 96, 89, and sentinel value -1

• Test the program again using scores 25, 500 (a mistake, instead of 50), 38, -500 (to correct the mistake), 50, 64, 78, and -1

• Does the program display the correct total points earned and grade?

• How many scores does the program say were entered?

Lab 7-3: Modify

An Introduction to Programming with C++, Seventh Edition 65

Page 337: c++Programming

• The code in Figure 7-53 should display the squares of the numbers from 1 through 5 (1, 4, 9, 16, and 25)

• Desk-check the code; did your desk-check reveal any errors?

• If so, correct the code and then desk-check it again

Lab 7-4: Desk-Check

An Introduction to Programming with C++, Seventh Edition 66

Figure 7-53 Code for Lab 7-4

Page 338: c++Programming

• Follow the instructions for starting C++ and opening the Lab7-5.cpp file

• Run the program and enter 15.45 when prompted

• The program goes into an infinite loop

• Type Ctrl+c to end the program

• Debug the program

Lab 7-5: Debug

An Introduction to Programming with C++, Seventh Edition 67

Page 339: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 8: More on the Repetition Structure

Page 340: c++Programming

• Include a posttest loop in pseudocode

• Include a posttest loop in a flowchart

• Code a posttest loop using the C++ do while

statement

• Nest repetition structures

• Raise a number to a power using the pow function

Objectives

An Introduction to Programming with C++, Seventh Edition 2

Page 341: c++Programming

• Repetition structures can be either pretest or posttest loops

• Pretest loop – condition evaluated before instructions are processed

• Posttest loop – condition evaluated after instructions are processed

• Posttest loop’s instructions are always processed at least once

• Pretest loop’s instructions may never be processed

Posttest Loops

An Introduction to Programming with C++, Seventh Edition 3

Page 342: c++Programming

An Introduction to Programming with C++, Seventh Edition 4

Figure 8-1 Problem specification, illustrations, and solutions

containing pretest and posttest loops

Posttest Loops (cont’d.)

Page 343: c++Programming

Posttest Loops (cont’d.)

An Introduction to Programming with C++, Seventh Edition 5

Figure 8-2 Selection structure added to Solution 2 from Figure 8-1

Page 344: c++Programming

• Decision symbol in a flowchart (a diamond) representing a repetition structure contains the loop condition

• Decision symbol appears at the top of a pretest loop, but at the bottom of a posttest loop

Flowcharting a Posttest Loop

An Introduction to Programming with C++, Seventh Edition 6

Page 345: c++Programming

An Introduction to Programming with C++, Seventh Edition 7

Figure 8-3 Wheels & More problem specification & algorithms (continues)

Flowcharting a Posttest Loop

(cont’d.)

Page 346: c++Programming

An Introduction to Programming with C++, Seventh Edition 8

Figure 8-3 Wheels & More problem

specification & algorithms (continued)

Flowcharting a Posttest Loop

(cont’d.)

Page 347: c++Programming

Flowcharting a Posttest Loop

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 9

Figure 8-4 Input and output items entered in the desk-check table

Figure 8-5 First hours worked and gross pay amounts recorded in

the desk-check table

Figure 8-7 Current status of the desk-check table

Page 348: c++Programming

• do while statement is used to code posttest loops in C++

• Syntax:

do {

one or more statements to be processed one time,

and thereafter as long as the condition is true

} while (condition);

• Some programmers use a comment (such as:

//begin loop) to mark beginning of loop

The do while Statement

An Introduction to Programming with C++, Seventh Edition 10

Page 349: c++Programming

• Programmer must provide loop condition

– Must evaluate to a Boolean value

– May contain variables, constants, functions, arithmetic operators, comparison operators, and logical operators

• Programmer must also provide statements to be executed when condition evaluates to true

• Braces are required around statements if there are more than one

The do while Statement (cont’d.)

An Introduction to Programming with C++, Seventh Edition 11

Page 350: c++Programming

An Introduction to Programming with C++, Seventh Edition 12

Figure 8-9 How to use the do while statement

The do while Statement (cont’d.)

Page 351: c++Programming

An Introduction to Programming with C++, Seventh Edition 13

Figure 8-9 How to use the do while statement (cont’d.)

The do while Statement (cont’d.)

Page 352: c++Programming

An Introduction to Programming with C++, Seventh Edition 14

Figure 8-10 IPO chart information and C++

instructions for the Wheels & More program

The do while Statement (cont’d.)

Page 353: c++Programming

An Introduction to Programming with C++, Seventh Edition 15

Figure 8-11 A sample run of the Wheels & More program

The do while Statement (cont’d.)

Page 354: c++Programming

• Like selection structures, repetition structures can be nested

• You can place one loop (the inner, or nested loop) inside another loop (the outer loop)

• Both loops can be pretest loops or posttest loops, or the two loops may be different types

• Programmer decides whether a problem requires a nested loop by analyzing the problem specification

Nested Repetition Structures

An Introduction to Programming with C++, Seventh Edition 16

Page 355: c++Programming

Nested Repetition Structures

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 17

Figure 8-12 Logic used by a clock’s minute and second hands

Page 356: c++Programming

Nested Repetition Structures

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 18

Figure 8-13 Problem specification and solution that requires a loop

Page 357: c++Programming

Nested Repetition Structures

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 19

Figure 8-14 Modified problem specification and

solution that requires a nested loop

Page 358: c++Programming

• Simple program that prints asterisks to the screen in different patterns

• First version contains a single loop

• Second version contains a nested loop

– Prints out three lines of five asterisks each using a nested for loop to print each line

The Asterisks Program

An Introduction to Programming with C++, Seventh Edition 20

Page 359: c++Programming

The Asterisks Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 21

Figure 8-15 Problem specification IPO chart information

and C++ instructions for the asterisks program

Page 360: c++Programming

The Asterisks Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 22

Figure 8-15 IPO chart information and C++ instructions

for the asterisks program (cont’d.)

Page 361: c++Programming

The Asterisks Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 23

Figure 8-17 Sample run of the asterisks program

Figure 8-16 Completed desk-check table for the asterisks program

Page 362: c++Programming

The Asterisks Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 24

Figure 8-18 Problem specification, IPO chart information,

and C++ instructions for the modified asterisks program

Page 363: c++Programming

An Introduction to Programming with C++, Seventh Edition 25

Figure 8-18 Problem specification, IPO chart information, and

C++ instructions for the modified asterisks program (cont.)

The Asterisks Program (cont’d.)

Page 364: c++Programming

The Asterisks Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 26

Figure 8-19 Desk-check table and output after the nested loop’s cout statement is processed the first time

Figure 8-20 Desk-check table and output after the nested loop’s cout statement is processed the second time

Page 365: c++Programming

The Asterisks Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 27

Figure 8-21 Current status of the desk-check table and output

Figure 8-22 Desk-check table and output after the

nested loop ends the second time

Page 366: c++Programming

The Asterisks Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 28

Figure 8-23 Desk-check table and output after

the nested loop ends the third time

Page 367: c++Programming

The Asterisks Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 29

Figure 8-24 Sample run of the modified asterisks program

Page 368: c++Programming

• Calculate the value of a one-time deposit into a savings account after some period of time

• Program uses an exponential formula to calculate the total account value some number of years after the initial investment given the investment amount and the annual interest rate

The Savings Calculator Program

An Introduction to Programming with C++, Seventh Edition 30

Page 369: c++Programming

The Savings Calculator Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 31

Figure 8-25 Problem specification, sample calculations, IPO chart,

and desk-check table for the savings calculator program

Page 370: c++Programming

An Introduction to Programming with C++, Seventh Edition 32

Figure 8-26 Flowchart for the savings calculator program

The Savings Calculator Program

(cont’d.)

Page 371: c++Programming

• The pow function is a convenient tool to raise a number to a power (exponentiation)

• The pow function raises a number to a power and returns the result as a double number

• Syntax is pow(x, y), in which x is the base and y is the exponent

• At least one of the two arguments must be a double

• Program must contain the #include <cmath> directive to use the pow function

The pow Function

An Introduction to Programming with C++, Seventh Edition 33

Page 372: c++Programming

An Introduction to Programming with C++, Seventh Edition 34

Figure 8-27 How to use the pow function

The pow Function (cont’d.)

Page 373: c++Programming

• Solution to the savings calculator problem and its corresponding C++ code (following slides)

• Code uses the pow function to calculate the total account value some number of years after the initial investment given a fixed annual interest rate of 2%

Coding the Savings Calculator

Program

An Introduction to Programming with C++, Seventh Edition 35

Page 374: c++Programming

An Introduction to Programming with C++, Seventh Edition 36

Figure 8-28 IPO chart information and C++ instructions

for the savings calculator program

Coding the Savings Calculator

Program (cont’d.)

Page 375: c++Programming

An Introduction to Programming with C++, Seventh Edition 37

Figure 8-28 IPO chart information and C++ instructions

for the savings calculator program

Coding the Savings Calculator

Program (cont’d.)

Page 376: c++Programming

An Introduction to Programming with C++, Seventh Edition 38

Figure 8-29 Savings calculator program

Coding the Savings Calculator

Program (cont’d.)

Page 377: c++Programming

Coding the Savings Calculator

Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 39

Figure 8-30 Sample run of savings calculator program

Page 378: c++Programming

• Savings calculator program is modified to calculate the total account value for interest rates of 2%, 3%, and 4%

Modifying the Savings Calculator

Program

An Introduction to Programming with C++, Seventh Edition 40

Page 379: c++Programming

Modifying the Savings Calculator

Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 41

Figure 8-31 IPO chart information and C++ instructions

for the modified savings calculator program

Page 380: c++Programming

An Introduction to Programming with C++, Seventh Edition 42

Figure 8-31 Modified IPO chart information and C++ instructions (cont’d.)

Modifying the Savings Calculator

Program (cont’d.)

Page 381: c++Programming

An Introduction to Programming with C++, Seventh Edition 43

Figure 8-32 Flowchart for the modified savings calculator program

Modifying the Savings Calculator

Program (cont’d.)

Page 382: c++Programming

An Introduction to Programming with C++, Seventh Edition 44

Figure 8-33 Modified savings calculator program

Modifying the Savings Calculator

Program (cont’d.)

Page 383: c++Programming

Modifying the Savings Calculator

Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 45

Figure 8-34 Sample run of modified savings calculator program

Page 384: c++Programming

• A repetition structure can be either a pretest loop or a posttest loop

• In a pretest loop, the loop condition is evaluated before the instructions in the loop are processed

• In a posttest loop, the evaluation occurs after the instructions within the loop are processed

• Use the do while statement to code a posttest loop in C++

• Use either the while statement or the for statement to code a pretest loop in C++

Summary

An Introduction to Programming with C++, Seventh Edition 46

Page 385: c++Programming

• Repetition structures can be nested, which means one loop (called the inner or nested loop) can be placed inside another loop (called the outer loop)

• For nested repetition structures to work correctly, the entire inner loop must be contained within the outer loop

• You can use the built-in C++ pow function to raise a number to a power

• The pow function returns the result as a double

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 47

Page 386: c++Programming

• Study the program in Figure 8-36 and answer the questions

• The program displays the total sales made in Region 1 and the total sales made in Region 2

Lab 8-1: Stop and Analyze

An Introduction to Programming with C++, Seventh Edition 48

Page 387: c++Programming

Lab 8-2: Plan and Create

An Introduction to Programming with C++, Seventh Edition 49

Figure 8-37 Problem specification for Lab 8-2

Page 388: c++Programming

• Modify the program in Lab 8-2

• Change both loops to posttest loops

• Use the program to display the multiplication tables for the multiplicands 6, 9, and 2

Lab 8-3: Modify

An Introduction to Programming with C++, Seventh Edition 50

Page 389: c++Programming

• Desk-check the code in Figure 8-43

• What will the code display on the computer screen?

Lab 8-4: Desk-Check

An Introduction to Programming with C++, Seventh Edition 51

Figure 8-43 Code for Lab 8-4

Page 390: c++Programming

• Follow the instructions for starting C++ and opening the Lab8-5.cpp file

• Debug the program

Lab 8-5: Debug

An Introduction to Programming with C++, Seventh Edition 52

Page 391: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 9: Value-Returning Functions

Page 392: c++Programming

• Use the sqrt function to return the square root of a number

• Generate random numbers

• Create and invoke a function that returns a value

• Pass information by value to a function

• Write a function prototype

• Understand a variable’s scope and lifetime

Objectives

An Introduction to Programming with C++, Seventh Edition 2

Page 393: c++Programming

• A function is a block of code that performs a task

• Every C++ program contains at least one function (main)

– Most contain many functions

• Some functions are built-in functions (part of C++): defined in language libraries

• Others, called program-defined functions, are written by programmers; defined in a program

• Functions allow for blocks of code to be used many times in a program without having to duplicate code

Functions

An Introduction to Programming with C++, Seventh Edition 3

Page 394: c++Programming

• Functions also allow large, complex programs to be broken down into small, manageable sub-tasks

• Each sub-task is solved by a function, and thus different people can write different functions

• Many functions can then be combined into a single program

• Typically, main is used to call other functions, but any function can call any other function

Functions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 4

Page 395: c++Programming

An Introduction to Programming with C++, Seventh Edition 5

Figure 9-1 Illustrations of value-returning and void functions

Functions (cont’d.)

Page 396: c++Programming

• All functions are either value-returning or void

• All value-returning functions perform a task and then return precisely one value

• In most cases, the value is returned to the statement that called the function

• Typically, a statement that calls a function assigns the return value to a variable

– However, a return value could also be used in a comparison or calculation or could be printed to the screen

Value-Returning Functions

An Introduction to Programming with C++, Seventh Edition 6

Page 397: c++Programming

• Program that calculates and displays the length of a right triangle hypotenuse

• Program uses Pythagorean theorem

– Requires squaring and taking square root

• pow function can be used to square

• sqrt function can be used to take square root

• Both are built-in value-returning functions

The Hypotenuse Program

An Introduction to Programming with C++, Seventh Edition 7

Page 398: c++Programming

An Introduction to Programming with C++, Seventh Edition 8

Figure 9-2 Problem specification, calculation example,

and IPO chart for the hypotenuse program

The Hypotenuse Program (cont’d.)

Page 399: c++Programming

An Introduction to Programming with C++, Seventh Edition 9

Figure 9-3 Flowchart of the hypotenuse program

The Hypotenuse Program (cont’d.)

Page 400: c++Programming

• sqrt function is a built-in value-returning function that returns a number’s square root as a double

• Definition contained in cmath library

– Program must contain #include <cmath> to use it

• Syntax: sqrt(x), in which x is a double or float

– Here, x is an actual argument, which is an item of information a function needs to perform its task

• Actual arguments are passed to a function when called

Finding the Square Root of a Number

An Introduction to Programming with C++, Seventh Edition 10

Page 401: c++Programming

An Introduction to Programming with C++, Seventh Edition 11

Figure 9-4 How to use the sqrt function

Finding the Square Root of a Number

(cont’d.)

Page 402: c++Programming

An Introduction to Programming with C++, Seventh Edition 12

Figure 9-5 IPO chart information and C++

instructions for the hypotenuse program

Finding the Square Root of a Number

(cont’d.)

Page 403: c++Programming

An Introduction to Programming with C++, Seventh Edition 13

Figure 9-6 Hypotenuse program

Finding the Square Root of a Number

(cont’d.)

Page 404: c++Programming

Finding the Square Root of a Number

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 14

Figure 9-7 Sample run of hypotenuse program

Page 405: c++Programming

• Program that generates addition problems of the form “What is the sum of x and y?”

• Asks user to input answer, compares answer to correct answer, and displays whether correct or not

• Program requires generating random integers between 1 and 10

The Random Addition Problems

Program

An Introduction to Programming with C++, Seventh Edition 15

Page 406: c++Programming

The Random Addition Problems

Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 16

Figure 9-8 Problem specification for random addition problems program

Page 407: c++Programming

An Introduction to Programming with C++, Seventh Edition 17

Figure 9-8 IPO chart for random addition problems program

The Random Addition Problems

Program (cont’d.)

Page 408: c++Programming

An Introduction to Programming with C++, Seventh Edition 18

Figure 9-9 Flowchart for random addition problems program

The Random Addition Problems

Program (cont’d.)

Page 409: c++Programming

• C++ provides a pseudo-random number generator

– Produces a sequence of numbers that meet certain statistical requirements for randomness

– Numbers chosen uniformly from finite set of numbers

– Not truly random but sufficient for practical purposes

• Random number generator in C++: rand function

– Returns an integer between 0 and RAND_MAX, inclusive

– RAND_MAX is a built-in constant (>= 32767)

Generating Random Integers

An Introduction to Programming with C++, Seventh Edition 19

Page 410: c++Programming

• rand function’s syntax: rand()

– Doesn’t require any actual arguments, but parentheses are still required

• Expression: lowerBound + rand() % (upperBound – lowerBound + 1)

– Allows ranges other than 0 to RAND_MAX to be used

– Range is upperBound to lowerBound

• Initialize random number generator each time

– Otherwise, will produce the same sequence

Generating Random Integers

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 20

Page 411: c++Programming

An Introduction to Programming with C++, Seventh Edition 21

Figure 9-10 How to use the rand function

Generating Random Integers

(cont’d.)

Page 412: c++Programming

An Introduction to Programming with C++, Seventh Edition 22

Figure 9-11 How to generate random integers within a specific range

Generating Random Integers

(cont’d.)

Page 413: c++Programming

An Introduction to Programming with C++, Seventh Edition 23

Figure 9-11 How to generate random integers within a specific range (cont’d.)

Generating Random Integers

(cont’d.)

Page 414: c++Programming

• Use srand function (a void function) to initialize random number generator

• Syntax: srand(seed), in which seed is an integer actual argument that represents the starting point of the generator

– Commonly initialized using the time function

• Ensures unique sequence of numbers for each program run

Generating Random Integers

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 24

Page 415: c++Programming

• time function is a value-returning function that returns current time in number of seconds since January 1, 1970

– Returns a time_t object, so must be cast to an integer before passing to srand

– Program must contain #include <ctime> directive to use it

Generating Random Integers

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 25

Page 416: c++Programming

An Introduction to Programming with C++, Seventh Edition 26

Figure 9-12 How to use the srand function

Generating Random Integers

(cont’d.)

Page 417: c++Programming

An Introduction to Programming with C++, Seventh Edition 27

Figure 9-13 IPO chart information and C++ instructions

for the random addition problems program

Generating Random Integers

(cont’d.)

Page 418: c++Programming

An Introduction to Programming with C++, Seventh Edition 28

Figure 9-13 IPO chart information and C++ instructions

for the random addition problems program (cont’d.)

Generating Random Integers

(cont’d.)

Page 419: c++Programming

An Introduction to Programming with C++, Seventh Edition 29

Figure 9-14 Random addition problems program

Generating Random Integers

(cont’d.)

Page 420: c++Programming

An Introduction to Programming with C++, Seventh Edition 30

Figure 9-14 Random addition problems program (cont’d.)

Generating Random Integers

(cont’d.)

Page 421: c++Programming

An Introduction to Programming with C++, Seventh Edition 31

Figure 9-15 Sample run of random addition problems program

Generating Random Integers

(cont’d.)

Page 422: c++Programming

• A program-defined value-returning function definition is composed of a header and a body

• Header (first line) contains return data type, name of function, and an optional parameterList

– Rules for function names are same as for variables

– Good idea to use meaningful names that describe function’s purpose

– Memory locations in parameterList are called formal parameters

• Each stores an item of information passed to the function when it is called

Creating Program-Defined Value-

Returning Functions

An Introduction to Programming with C++, Seventh Edition 32

Page 423: c++Programming

• Function body contains instructions for performing the function’s assigned task

• Surrounded by braces ({})

• Last statement is usually the return statement

– Returns one value (must match return data type in function header)

• After return statement is processed, program execution continues in calling function

• Good idea to include comment (such as //end of

functionName) to mark end of function

Creating Program-Defined Value-

Returning Functions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 33

Page 424: c++Programming

An Introduction to Programming with C++, Seventh Edition 34

Figure 9-16 IPO charts for modified random addition problems program

Creating Program-Defined Value-

Returning Functions (cont’d.)

Page 425: c++Programming

An Introduction to Programming with C++, Seventh Edition 35

Figure 9-16 IPO charts for modified random addition problems program (cont’d.)

Creating Program-Defined Value-

Returning Functions (cont’d.)

Page 426: c++Programming

An Introduction to Programming with C++, Seventh Edition 36

Figure 9-17 How to create a program-defined value-returning function

Creating Program-Defined Value-

Returning Functions (cont’d.)

Page 427: c++Programming

An Introduction to Programming with C++, Seventh Edition 37

Figure 9-17 How to create a program-defined value-returning function (cont’d.)

Creating Program-Defined Value-

Returning Functions (cont’d.)

Page 428: c++Programming

• A function must be called (invoked) to perform its task

• main is automatically called when program is run

• Other functions must be called by a statement

• Syntax for calling a function: functionName([argumentList]);

– argumentList is list of actual arguments (if any)

– An actual argument can be a variable, named constant, literal constant, or keyword

Calling a Function

An Introduction to Programming with C++, Seventh Edition 38

Page 429: c++Programming

• Value-returning functions are typically called from statements that:

– Assign the return value to a variable

– Use the return value in a calculation or comparison

– Display the return value

• A call to a void function is an independent statement because void functions do not return values

Calling a Function (cont’d.)

An Introduction to Programming with C++, Seventh Edition 39

Page 430: c++Programming

• C++ allows you to pass either a variable’s value or its address to a function

• Passing a variable’s value is referred to as passing by value

• Passing a variable’s address is referred to as passing by reference

• Default is passing by value

• Number, data type, and ordering of actual arguments must match the formal parameters in function header

– Names do not need to match (different names are better)

Calling a Function (cont’d.)

An Introduction to Programming with C++, Seventh Edition 40

Page 431: c++Programming

An Introduction to Programming with C++, Seventh Edition 41

Figure 9-18 How to call a function

Calling a Function (cont’d.)

Page 432: c++Programming

An Introduction to Programming with C++, Seventh Edition 42

Figure 9-18 How to call a function (cont’d.)

Calling a Function (cont’d.)

Page 433: c++Programming

An Introduction to Programming with C++, Seventh Edition 43

Figure 9-19 Function calls and function definitions

Calling a Function (cont’d.)

Page 434: c++Programming

An Introduction to Programming with C++, Seventh Edition 44

Figure 9-20 IPO chart information and C++ instructions

for the modified random addition problems program

Calling a Function (cont’d.)

Page 435: c++Programming

An Introduction to Programming with C++, Seventh Edition 45

Figure 9-20 IPO chart information and C++ instructions

for the modified random addition problems program (cont’d.)

Calling a Function (cont’d.)

Page 436: c++Programming

An Introduction to Programming with C++, Seventh Edition 46

Figure 9-20 IPO chart information and C++ instructions

for the modified random addition problems program (cont’d.)

Calling a Function (cont’d.)

Page 437: c++Programming

An Introduction to Programming with C++, Seventh Edition 47

Figure 9-20 IPO chart information and C++ instructions

for the modified random addition problems program (cont’d.)

Calling a Function (cont’d.)

Page 438: c++Programming

• When a function definition appears below the main function, you must enter a function prototype above the main function

• A function prototype is a statement that specifies the function’s name, data type of its return value, and data type of each of its formal parameters (if any)

– Names for the formal parameters are not required

• Programmers usually place function prototypes at beginning of program, after the #include directives

Function Prototypes

An Introduction to Programming with C++, Seventh Edition 48

Page 439: c++Programming

An Introduction to Programming with C++, Seventh Edition 49

Figure 9-21 How to write a function prototype

Function Prototypes (cont’d.)

Page 440: c++Programming

An Introduction to Programming with C++, Seventh Edition 50

Figure 9-22 Modified random addition problems program

Function Prototypes (cont’d.)

Page 441: c++Programming

An Introduction to Programming with C++, Seventh Edition 51

Figure 9-22 Modified random addition problems program (cont’d.)

Function Prototypes (cont’d.)

Page 442: c++Programming

• Modification of the random addition problems program

• User should have the option to specify the range of random numbers that the program generates

• Program’s tasks are divided up into functions

The Western Elementary School

Program

An Introduction to Programming with C++, Seventh Edition 52

Page 443: c++Programming

An Introduction to Programming with C++, Seventh Edition 53

Figure 9-23 Western Elementary School program

The Western Elementary School

Program (cont’d.)

Page 444: c++Programming

An Introduction to Programming with C++, Seventh Edition 54

Figure 9-23 Western Elementary School program (cont’d.)

The Western Elementary School

Program (cont’d.)

Page 445: c++Programming

An Introduction to Programming with C++, Seventh Edition 55

Figure 9-24 Sample run of Western Elementary School program

The Western Elementary School

Program (cont’d.)

Page 446: c++Programming

• Program that uses a program-defined, value-returning function to calculate the area of a rectangle

• Input is rectangle’s length and width measurements

• Program calculates area and then displays it on the screen

The Area Calculator Program

An Introduction to Programming with C++, Seventh Edition 56

Page 447: c++Programming

An Introduction to Programming with C++, Seventh Edition 57

Figure 9-25 Problem specification and IPO charts for area calculator program

The Area Calculator Program

(cont’d.)

Page 448: c++Programming

An Introduction to Programming with C++, Seventh Edition 58

Figure 9-25 Problem specification and IPO charts

for the area calculator program (cont’d.)

The Area Calculator Program

(cont’d.)

Page 449: c++Programming

An Introduction to Programming with C++, Seventh Edition 59

Figure 9-26 Sample run of the area calculator program

The Area Calculator Program

(cont’d.)

Page 450: c++Programming

An Introduction to Programming with C++, Seventh Edition 60

Figure 9-27 Area calculator program

The Area Calculator Program

(cont’d.)

Page 451: c++Programming

An Introduction to Programming with C++, Seventh Edition 61

Figure 9-28 Desk-check table after statements

on lines 12 through 19 are processed

Figure 9-29 Desk-check table after function header getRectangleArea is processed

The Area Calculator Program

(cont’d.)

Page 452: c++Programming

An Introduction to Programming with C++, Seventh Edition 62

Figure 9-30 Desk-check table after getRectangleArea function ends

The Area Calculator Program

(cont’d.)

Page 453: c++Programming

• A variable’s scope indicates where in the program the variable can be used

• A variable’s lifetime indicates how long the variable remains in the computer’s internal memory

• Both scope and lifetime are determined by where you declare the variable in the program

• Variables declared within a function and those that appear in a function’s parameterList have a local scope and are referred to as local variables

The Scope and Lifetime of a Variable

An Introduction to Programming with C++, Seventh Edition 63

Page 454: c++Programming

• Local variables can be used only by the function in which they are declared or in whose parameterList they appear

– Remain in internal memory until the function ends

• Global variables are declared outside of any function in the program

– Remain in memory until the program ends

• Any statement can use a global variable

The Scope and Lifetime of a Variable

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 64

Page 455: c++Programming

• Declaring a variable as global can allow unintentional errors to occur

– e.g., a function that should not have access to the variable inadvertently changes the variable’s contents

• You should avoid using global variables unless necessary

• If more than one function needs to access the same variable, it is better to create a local variable in one function and pass it to other functions that need it

The Scope and Lifetime of a Variable

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 65

Page 456: c++Programming

• Program that calculates a salesperson’s bonus (5% of his or her sales)

– Uses two program-defined, value-returning functions

– Illustrates how, when two memory locations have the same name, the position of a statement that uses the name determines which location is used (based on scope)

The Bonus Calculator Program

An Introduction to Programming with C++, Seventh Edition 66

Page 457: c++Programming

An Introduction to Programming with C++, Seventh Edition 67

Figure 9-31 Problem specification, IPO chart information, and C++ code for the main function

The Bonus Calculator Program

(cont’d.)

Page 458: c++Programming

An Introduction to Programming with C++, Seventh Edition 68

Figure 9-32 IPO chart information and C++ code for the getSales function

The Bonus Calculator Program

(cont’d.)

Page 459: c++Programming

An Introduction to Programming with C++, Seventh Edition 69

Figure 9-33 IPO chart information and C++ code for the getBonus function

The Bonus Calculator Program

(cont’d.)

Page 460: c++Programming

An Introduction to Programming with C++, Seventh Edition 70

Figure 9-35 Bonus calculator program

The Bonus Calculator Program

(cont’d.)

Page 461: c++Programming

An Introduction to Programming with C++, Seventh Edition 71

Figure 9-35 Bonus calculator program (cont’d.)

The Bonus Calculator Program

(cont’d.)

Page 462: c++Programming

An Introduction to Programming with C++, Seventh Edition 72

Figure 9-34 Sample run of bonus calculator program

Figure 9-36 Desk-check table after variable declaration

statements on lines 14 & 15 are processed

The Bonus Calculator Program

(cont’d.)

Page 463: c++Programming

An Introduction to Programming with C++, Seventh Edition 73

Figure 9-37 Desk-check table after the sales amount is entered

Figure 9-38 Desk-check table after the sales amount is returned to the main function

The Bonus Calculator Program

(cont’d.)

Page 464: c++Programming

An Introduction to Programming with C++, Seventh Edition 74

Figure 9-39 Desk-check table after getSales function ends

Figure 9-40 Desk-check table after getBonus function header is processed

The Bonus Calculator Program

(cont’d.)

Page 465: c++Programming

An Introduction to Programming with C++, Seventh Edition 75

Figure 9-41 Desk-check table after bonus is calculated

Figure 9-42 Desk-check table after getBonus function ends

The Bonus Calculator Program

(cont’d.)

Page 466: c++Programming

• Functions

– Allow programmers to avoid duplicating code

– Allow for large, complex programs to be broken into small, manageable tasks

• Some functions are built into the language, and others are program-defined

• All functions are either value-returning or void

• A value-returning function returns one value

– Value returned to statement that called the function

• A void function returns no value

Summary

An Introduction to Programming with C++, Seventh Edition 76

Page 467: c++Programming

• Use the sqrt function to find the square root of a number

• Items in parentheses in a function call are called actual arguments

• The rand function is used to generate random numbers

– Returns an integer between 0 and RAND_MAX

• srand function is used to initialize rand function

– time function usually used as seed (starting point)

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 77

Page 468: c++Programming

• Function definition composed of header and body

• Header specifies function name, return data type, and formal parameter names and types (if any)

– Data types and ordering of formal parameters must match data types and ordering of actual arguments

• Body contains instructions for performing the function’s assigned task

– Surrounded by braces ({})

• return statement returns the result of an expression to the calling function

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 78

Page 469: c++Programming

• You call a function by including its name and actual arguments (if any) in a statement

• Variables in C++ are passed by value by default

• A function prototype must be provided for each function defined below the main function

• Scope of a variable indicates where in the program it can be used

• Lifetime of a variable indicates how long it will stay in internal memory

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 79

Page 470: c++Programming

• Local variables can be used only within the function in which they are declared or in whose parameterList they appear

– Remain in memory until the function ends

• Global variables can be used anywhere

– Remain in memory until the program ends

• If more than one memory location have the same name, position of the statement in which the name is used determines which location is used

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 80

Page 471: c++Programming

• Study the program in Figure 9-43, and then answer the questions

Lab 9-1: Stop and Analyze

An Introduction to Programming with C++, Seventh Edition 81

Page 472: c++Programming

Lab 9-2: Plan and Create

An Introduction to Programming with C++, Seventh Edition 82

Figure 9-44 Problem specification for Lab 9-2

Page 473: c++Programming

• Modify the program from Lab 9-2 in three ways:

– Allow user to enter an interest rate either as a whole number or a decimal

– Program should compare both monthly payments and display one of three messages

– The user should be able to calculate the monthly payments as many times as needed without having to run the program multiple times

Lab 9-3: Modify

An Introduction to Programming with C++, Seventh Edition 83

Page 474: c++Programming

• Desk-check the code in Figure 9-51 using the data: Beginning balance: 2000

w, 400, y

D, 1200, y

W, 45, y

w, 55, y

k, y

w, 150, y

d, 15, y

W, 1050, n

• What current balance will the code display on the screen?

Lab 9-4: Desk-Check

An Introduction to Programming with C++, Seventh Edition 84

Page 475: c++Programming

• Test the program in the Lab9-5.cpp file using the data 20500, 3500, and 10 as the asset cost, salvage value, and useful life

• The depreciation should be $1700.00

• Debug the program

Lab 9-5: Debug

An Introduction to Programming with C++, Seventh Edition 85

Page 476: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 10: Void Functions

Page 477: c++Programming

• Create a void function

• Invoke a void function

• Pass information by reference to a function

Objectives

An Introduction to Programming with C++, Seventh Edition 2

Page 478: c++Programming

• Recall that value-returning functions perform a task and then return a single value

• Void functions also perform tasks but do not return a value

• A void function may be used to do something like display information on the screen

– Doesn’t need to return a value

Functions

An Introduction to Programming with C++, Seventh Edition 3

Page 479: c++Programming

An Introduction to Programming with C++, Seventh Edition 4

Figure 10-1 Illustration of value-returning and void functions

Functions (cont’d.)

Page 480: c++Programming

An Introduction to Programming with C++, Seventh Edition 5

Figure 10-2 How to create a program-defined void function

Creating Program-Defined Void

Functions

Page 481: c++Programming

• Note that header begins with keyword void, instead of a return data type

– Indicates that the function does not return a value

• Function body does not contain a return statement

• Call a void function by including its name and actual arguments (if any) in a statement

• Call to a void function appears as a self-contained statement, not part of another statement

• Execution is same as for value-returning functions

Creating Program-Defined Void

Functions (cont’d.)

An Introduction to Programming with C++, Seventh Edition 6

Page 482: c++Programming

An Introduction to Programming with C++, Seventh Edition 7

Figure 10-4 IPO chart information and C++

instructions for the ABC Company program

Creating Program-Defined Void

Functions (cont’d.)

Page 483: c++Programming

An Introduction to Programming with C++, Seventh Edition 8

Figure 10-4 IPO chart information and C++

instructions for the ABC Company program (cont’d.)

Creating Program-Defined Void

Functions (cont’d.)

Page 484: c++Programming

An Introduction to Programming with C++, Seventh Edition 9

Figure 10-4 IPO chart information and C++

instructions for the ABC Company program (cont’d.)

Creating Program-Defined Void

Functions (cont’d.)

Page 485: c++Programming

An Introduction to Programming with C++, Seventh Edition 10

Figure 10-4 IPO chart information and C++

instructions for the ABC Company program (cont’d.)

Creating Program-Defined Void

Functions (cont’d.)

Page 486: c++Programming

An Introduction to Programming with C++, Seventh Edition 11

Figure 10-4 IPO chart information and C++

instructions for the ABC Company program (cont’d.)

Creating Program-Defined Void

Functions (cont’d.)

Page 487: c++Programming

An Introduction to Programming with C++, Seventh Edition 12

Figure 10-5 ABC Company program

Creating Program-Defined Void

Functions (cont’d.)

Page 488: c++Programming

An Introduction to Programming with C++, Seventh Edition 13

Figure 10-5 ABC Company program (cont’d.)

Creating Program-Defined Void

Functions (cont’d.)

Page 489: c++Programming

An Introduction to Programming with C++, Seventh Edition 14

Figure 10-6 Sample run of the ABC Company program

Creating Program-Defined Void

Functions (cont’d.)

Page 490: c++Programming

• Recall you can pass a variable’s value or its address

• Passing a variable’s value is referred to as passing by value, while passing a variable’s address is referred to as passing by reference

• Which one you choose depends on whether the receiving function should have access to the variable in memory

• Passing by value will not permit the function to change the contents of the variable, but passing by reference will

Passing Variables to a Function

An Introduction to Programming with C++, Seventh Edition 15

Page 491: c++Programming

• Passing a variable by value means that only a copy of the variable’s contents is passed, not the address of the variable

• This means that the receiving function cannot change the contents of the variable

• It is thus appropriate to pass by value when the receiving function needs to know the value of the variable but does not need to change it

Reviewing Passing Variables by Value

An Introduction to Programming with C++, Seventh Edition 16

Page 492: c++Programming

An Introduction to Programming with C++, Seventh Edition 17

Figure 10-8 Age message program

Reviewing Passing Variables by Value

(cont’d.)

Page 493: c++Programming

An Introduction to Programming with C++, Seventh Edition 18

Figure 10-10 Desk-check table after the displayAge function header is processed

Figure 10-9 Desk-check table after the first three statements in the main function are processed

Reviewing Passing Variables by Value

(cont’d.)

Page 494: c++Programming

An Introduction to Programming with C++, Seventh Edition 19

Figure 10-12 Sample run of the age message program

Figure 10-11 Desk-check table after the displayAge function ends

Reviewing Passing Variables by Value

(cont’d.)

Page 495: c++Programming

• Passing a variable’s address in internal memory to a function is referred to as passing by reference

• You pass by reference when you want the receiving function to change the contents of the variable

• To pass by reference in C++, you include an ampersand (&) before the name of the formal parameter in the receiving function’s header

• Ampersand (&) is the address-of operator

– Tells the computer to pass the variable’s address rather than a copy of its contents

Passing Variables by Reference

An Introduction to Programming with C++, Seventh Edition 20

Page 496: c++Programming

• If receiving function appears below main, you must also include the & in the receiving function’s prototype

• You enter the & immediately before the name of the formal parameter in the prototype

– If the prototype does not contain the formal parameter’s name, you enter a space followed by & after the formal parameter’s data type

• Void functions use variables passed by reference to send information back to the calling function, instead of a return value

Passing Variables by Reference

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 21

Page 497: c++Programming

An Introduction to Programming with C++, Seventh Edition 22

Figure 10-13 Modified age message program

Passing Variables by Reference

(cont’d.)

Page 498: c++Programming

An Introduction to Programming with C++, Seventh Edition 23

Figure 10-15 Desk-check table after the getAge function header is processed

Figure 10-14 Desk-check table after the declaration statement in the main function is processed

Passing Variables by Reference

(cont’d.)

Page 499: c++Programming

An Introduction to Programming with C++, Seventh Edition 24

Figure 10-17 Desk-check table after the getAge function ends

Figure 10-16 Desk-check table after the statements in the getAge function are processed

Passing Variables by Reference

(cont’d.)

Page 500: c++Programming

An Introduction to Programming with C++, Seventh Edition 25

Figure 10-19 Desk-check table after the displayAge function ends

Figure 10-18 Desk-check table after the computer processes the displayAge function header

Passing Variables by Reference

(cont’d.)

Page 501: c++Programming

An Introduction to Programming with C++, Seventh Edition 26

Figure 10-20 Sample run of the modified age message program

Passing Variables by Reference

(cont’d.)

Page 502: c++Programming

• Program that allows the user to enter an employee’s current salary and raise rate

• Computes the employee’s raise and new salary

• Program makes use of a void function that is passed two variables by value and two by reference

The Salary Program

An Introduction to Programming with C++, Seventh Edition 27

Page 503: c++Programming

The Salary Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 28

Figure 10-22 IPO chart information and C++

instructions for the salary program

Page 504: c++Programming

An Introduction to Programming with C++, Seventh Edition 29

Figure 10-22 IPO chart information and C++

instructions for the salary program (cont’d.)

The Salary Program (cont’d.)

Page 505: c++Programming

An Introduction to Programming with C++, Seventh Edition 30

Figure 10-23 Salary program

The Salary Program (cont’d.)

Page 506: c++Programming

An Introduction to Programming with C++, Seventh Edition 31

Figure 10-23 Salary program (cont’d.)

The Salary Program (cont’d.)

Page 507: c++Programming

An Introduction to Programming with C++, Seventh Edition 32

Figure 10-25 Desk-check table after the computer processes the getNewPayInfo function header

Figure 10-24 Desk-check table after the statements

on lines 15 through 24 are processed

The Salary Program (cont’d.)

Page 508: c++Programming

An Introduction to Programming with C++, Seventh Edition 33

Figure 10-27 Desk-check table after the getNewPayInfo function ends

Figure 10-26 Desk-check table after the computer processes the statements in the getNewPayInfo function body

The Salary Program (cont’d.)

Page 509: c++Programming

An Introduction to Programming with C++, Seventh Edition 34

Figure 10-28 Sample run of the salary program

The Salary Program (cont’d.)

Page 510: c++Programming

• All functions are either void or value-returning

• Value-returning functions return one value

• Void functions do not return a value

• Function header of a void function begins with the keyword void instead of a return data type

• Function body of a void function does not contain a return statement

• You call a void function by including its name and actual arguments in a statement

Summary

An Introduction to Programming with C++, Seventh Edition 35

Page 511: c++Programming

• A call to a void function appears as a statement by itself rather than as part of another statement

• Variables can be passed to functions either by value (the default) or by reference

• When a variable is passed by value, only a copy of the variable’s value is passed

– Receiving function is not given access to the variable, so it cannot change the variable’s contents

– Computer uses data type and name of formal parameter to store a copy of the value

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 36

Page 512: c++Programming

• When a variable is passed by reference, the variable’s address in memory is passed

– Receiving function can change variable’s contents

– Computer assigns name of formal parameter to memory location – variable then has two names

• To pass by reference you include the address-of operator (&) before the name of the formal parameter in function header

• If function appears below main, you must also include the & in the function’s prototype

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 37

Page 513: c++Programming

• Study the code in Figure 10-30 and then answer the questions (sample run below)

Lab 10-1: Stop and Analyze

An Introduction to Programming with C++, Seventh Edition 38

Figure 10-29 Sample run of program for Lab 10-1

Page 514: c++Programming

Lab 10-2: Plan and Create

An Introduction to Programming with C++, Seventh Edition 39

Figure 10-31 Problem specification and a sample calculation for Lab 10-2

Page 515: c++Programming

• Make a copy of Lab 10-2 to modify

• Current version uses one void function to calculate both the number of units used and the total charge

• Replace the calcBill functions with two functions:

– A void function getUnits that calculates the total number of units used

– A value-returning function getTotal that calculates and returns the total charge

• Test the program appropriately

Lab 10-3: Modify

An Introduction to Programming with C++, Seventh Edition 40

Page 516: c++Programming

• Desk-check the code in Figure 10-37 using the following four sets of test scores:

– 78 and 85

– 45 and 93

– 87 and 98

– 54 and 32

Lab 10-4: Desk-Check

An Introduction to Programming with C++, Seventh Edition 41

Page 517: c++Programming

• Run the program in the Lab10-5.cpp file

• Enter the following scores: 93, 90, 85, and 100

• The program should display 368 as the total points and A as the grade

• Debug the program

Lab 10-5: Debug

An Introduction to Programming with C++, Seventh Edition 42

Page 518: c++Programming

Introduction to Programming in C++

Seventh Edition

Chapter 11: One-Dimensional Arrays

Page 519: c++Programming

• Declare and initialize a one-dimensional array

• Enter data into a one-dimensional array

• Display the contents of a one-dimensional array

• Pass a one-dimensional array to a function

• Calculate the total and average of the values in a one-dimensional array

Objectives

An Introduction to Programming with C++, Seventh Edition 2

Page 520: c++Programming

• Search a one-dimensional array

• Access an individual element in a one-dimensional array

• Find the highest value in a one-dimensional array

• Explain the bubble sort algorithm

• Use parallel one-dimensional arrays

Objectives (cont’d.)

An Introduction to Programming with C++, Seventh Edition 3

Page 521: c++Programming

• A simple variable (also called a scalar variable) is unrelated to any other variable in memory

• Sometimes variables are related to each other

• Easier and more efficient to treat these as a group

• A group of related variables with the same data type is referred to as an array

Arrays

An Introduction to Programming with C++, Seventh Edition 4

Page 522: c++Programming

• Storing data in an array increases the efficiency of a program

– Data can be accessed from internal memory faster than it can be from a file on a disk

– Once stored in an array, data can be used as many times as necessary without having to enter it again

• Variables in an array can be used like any other

• Most commonly used arrays in business applications are one-dimensional and two-dimensional

Arrays (cont’d.)

An Introduction to Programming with C++, Seventh Edition 5

Page 523: c++Programming

• Variables in an array are stored in consecutive locations in computer’s internal memory

• Each variable in an array has the same name and data type

• You distinguish one variable in a one-dimensional array from another variable in the same array by using a unique integer, called a subscript

• A subscript indicates a variable’s position in the array and is assigned by the computer when the array is created

One-Dimensional Arrays

An Introduction to Programming with C++, Seventh Edition 6

Page 524: c++Programming

• First variable in a one-dimensional array is assigned a subscript of 0, second a subscript of 1, and so on

• You refer to a variable in an array by the array’s name immediately followed by a subscript enclosed in square brackets (e.g., sales[0])

• The last subscript in an array is always one less than the total number of variables in the array, since the subscripts begin at 0

One-Dimensional Arrays (cont’d.)

An Introduction to Programming with C++, Seventh Edition 7

Page 525: c++Programming

An Introduction to Programming with C++, Seventh Edition 8

Figure 11-1 Illustration of naming conventions for one-dimensional beatles array

One-Dimensional Arrays (cont’d.)

Page 526: c++Programming

An Introduction to Programming with C++, Seventh Edition 9

Figure 11-2 Illustration of naming conventions for one-dimensional sales array

One-Dimensional Arrays (cont’d.)

Page 527: c++Programming

One-Dimensional Arrays (cont’d.)

An Introduction to Programming with C++, Seventh Edition 10

Figure 11-3 Problem specification and IPO chart

for the XYZ Company’s sales program

Page 528: c++Programming

• Must declare an array before you can use it

• Also good programming practice to initialize array variables

• Syntax for declaring and initializing a one-dimensional array is:

dataType arrayName [numberOfElements] = {initialValues};

– dataType is the type of data that the array variables (elements) will store

– arrayName is name of array (same rules for naming an array as for naming a variable)

Declaring and Initializing a One-

Dimensional Array

An Introduction to Programming with C++, Seventh Edition 11

Page 529: c++Programming

• numberOfElements is an integer specifying the size of the array (enclosed in square brackets)

• You may initialize array elements by entering one or more values, separated by commas, in braces

• Assigning initial values is referred to as populating the array

• The values used to populate an array should have the same data type as the array variables

– Otherwise, implicit type conversion is performed

Declaring and Initializing a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 12

Page 530: c++Programming

• Most C++ compilers initialize uninitialized numeric array elements to 0.0 or 0 (depending on data type)

• Automatic initialization is only done if you provide at least one value in the initialValues section

• Be sure to include an appropriate number of initial values

– Providing too many will cause a compiler error or incorrectly assign adjacent memory locations

Declaring and Initializing a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 13

Page 531: c++Programming

An Introduction to Programming with C++, Seventh Edition 14

Figure 11-4 How to declare and initialize a one-dimensional array

Declaring and Initializing a One-

Dimensional Array (cont’d.)

Page 532: c++Programming

• You can use an assignment statement or the extraction operator to enter data into an array element

• Syntax of assignment statement is:

arrayName[subscript] = expression;

– expression can include any combination of constants, variables, and operators

– Data type of expression must match data type of array; otherwise, implicit type conversion will occur

Entering Data into a One-Dimensional

Array

An Introduction to Programming with C++, Seventh Edition 15

Page 533: c++Programming

An Introduction to Programming with C++, Seventh Edition 16

Figure 11-5 How to use an assignment statement

to assign data to a one-dimensional array

Entering Data into a One-Dimensional

Array (cont’d.)

Page 534: c++Programming

An Introduction to Programming with C++, Seventh Edition 17

Figure 11-5 How to use an assignment statement

to assign data to a one-dimensional array (cont.)

Entering Data into a One-Dimensional

Array (cont’d.)

Page 535: c++Programming

Entering Data into a One-Dimensional

Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 18

Figure 11-6 How to use the extraction operator

to store data in a one-dimensional array

Page 536: c++Programming

Entering Data into a One-Dimensional

Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 19

Figure 11-6 How to use the extraction operator

to store data in a one-dimensional array (cont.)

Page 537: c++Programming

• To display the contents of an array, you need to access each of its elements

• Use a loop along with a counter variable that keeps track of each subscript in the array

Displaying the Contents of a One-

Dimensional Array

An Introduction to Programming with C++, Seventh Edition 20

Page 538: c++Programming

Displaying the Contents of a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 21

Figure 11-7 How to display the contents of a one-dimensional array

Page 539: c++Programming

Displaying the Contents of a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 22

Figure 11-7 How to display the contents of a one-dimensional array (cont.)

Page 540: c++Programming

• Program uses an array to store the sales made in each of the XYZ Company’s four regions

• Allows the user to enter the sales amounts and then displays the amounts on the computer screen

Coding the XYZ Company’s Sales

Program

An Introduction to Programming with C++, Seventh Edition 23

Page 541: c++Programming

An Introduction to Programming with C++, Seventh Edition 24

Figure 11-8 IPO chart information and C++ instructions

for the XYZ Company’s sales program

Coding the XYZ Company’s Sales

Program (cont’d.)

Page 542: c++Programming

An Introduction to Programming with C++, Seventh Edition 25

Figure 11-9 The XYZ Company’s sales program

Coding the XYZ Company’s Sales

Program (cont’d.)

Page 543: c++Programming

Coding the XYZ Company’s Sales

Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 26

Figure 11-10 Sample run of XYZ Company’s sales program

Page 544: c++Programming

Coding the XYZ Company’s Sales

Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 27

Figure 11-11 Desk-check table after the

array declaration statement is processed

Figure 11-12 Desk-check table after the

initialization argument on line 15 is processed

Page 545: c++Programming

Coding the XYZ Company’s Sales

Program (cont’d.)

An Introduction to Programming with C++, Seventh Edition 28

Figure 11-13 Desk-check table after Region 1’s sales entered in array

Figure 11-15 Desk-check table after Region 3’s sales entered in array

Figure 11-14 Desk-check table after Region 2’s sales entered in array

Page 546: c++Programming

An Introduction to Programming with C++, Seventh Edition 29

Figure 11-17 Desk-check table after for loop on lines 15-20 ends

Figure 11-16 Desk-check table after Region 4’s sales entered in array

Coding the XYZ Company’s Sales

Program (cont’d.)

Page 547: c++Programming

An Introduction to Programming with C++, Seventh Edition 30

Figure 11-19 Desk-check table after the for loop on lines 23 through 27 ends

Figure 11-18 Desk-check table after the

initialization argument on line 23 is processed

Coding the XYZ Company’s Sales

Program (cont’d.)

Page 548: c++Programming

• You can pass an array to a function by including the array’s name as the actual argument

• Unless specified otherwise, scalar variables in C++ are passed by value

• Arrays, however, are passed by reference by default, because it is more efficient

• Passing an array by value would require copying the entire array, which could be very large

Passing a One-Dimensional Array to a

Function

An Introduction to Programming with C++, Seventh Edition 31

Page 549: c++Programming

• Passing an array by reference allows the computer to pass the address of only the first array element

– Since elements are stored in contiguous memory locations, computer can use this address to locate remaining elements in the array

• Indicate that you are passing an array by entering formal parameter’s name and data type, followed by empty square brackets

– Address-of operator (&) is not needed in function header or function prototype, since arrays are passed by reference by default

Passing a One-Dimensional Array to a

Function (cont’d.)

An Introduction to Programming with C++, Seventh Edition 32

Page 550: c++Programming

An Introduction to Programming with C++, Seventh Edition 33

Figure 11-20 XYZ Company’s modified sales program

Passing a One-Dimensional Array to a

Function (cont’d.)

Page 551: c++Programming

Passing a One-Dimensional Array to a

Function (cont’d.)

An Introduction to Programming with C++, Seventh Edition 34

Figure 11-20 XYZ Company’s modified sales program (cont’d.)

Page 552: c++Programming

An Introduction to Programming with C++, Seventh Edition 35

Figure 11-21 Completed desk-check table for

the XYZ Company’s modified sales program

Passing a One-Dimensional Array to a

Function (cont’d.)

Page 553: c++Programming

• Program displays total and average number of pounds of coffee used in a 12-month period by the Moonbucks Coffee Company

• Stores monthly usage amount in a 12-element double array named pounds

• Uses a program-defined value-returning function named getTotal to calculate total usage for the year

The Moonbucks Coffee Program—

Calculating a Total and Average

An Introduction to Programming with C++, Seventh Edition 36

Page 554: c++Programming

An Introduction to Programming with C++, Seventh Edition 37

Figure 11-22 Problem specification, IPO chart information,

and C++ instructions for the Moonbucks Coffee program

The Moonbucks Coffee Program

(cont’d.)

Page 555: c++Programming

The Moonbucks Coffee Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 38

Figure 11-22 Problem specification, IPO chart information, and

C++ instructions for the Moonbucks Coffee program (cont’d.)

Page 556: c++Programming

The Moonbucks Coffee Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 39

Figure 11-22 Problem specification, IPO chart information, and

C++ instructions for the Moonbucks Coffee program (cont’d.)

Page 557: c++Programming

An Introduction to Programming with C++, Seventh Edition 40

Figure 11-23 Moonbucks Coffee program

The Moonbucks Coffee Program

(cont’d.)

Page 558: c++Programming

An Introduction to Programming with C++, Seventh Edition 41

Figure 11-23 Moonbucks Coffee program (cont’d.)

The Moonbucks Coffee Program

(cont’d.)

Page 559: c++Programming

The Moonbucks Coffee Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 42

Figure 11-24 Result of running the Moonbucks Coffee program

Page 560: c++Programming

• Program displays number of employees whose salary is greater than an amount entered by user

• Stores employees’ salaries in a 10-element int array named salaries

• Uses a loop to search through salaries array and a selection structure to compare salary in current element with salary entered by user

– Increments a counter if the current salary is greater than the one entered by the user

The JK Motors Program—Searching an

Array

An Introduction to Programming with C++, Seventh Edition 43

Page 561: c++Programming

An Introduction to Programming with C++, Seventh Edition 44

Figure 11-25 Problem specification, IPO chart information,

and C++ instructions for the JK motors program

The JK Motors Program—Searching an

Array (cont’d.)

Page 562: c++Programming

An Introduction to Programming with C++, Seventh Edition 45

Figure 11-25 Problem specification, IPO chart information,

and C++ instructions for the JK motors program (cont’d.)

The JK Motors Program—Searching an

Array (cont’d.)

Page 563: c++Programming

An Introduction to Programming with C++, Seventh Edition 46

Figure 11-26 JK motors program

The JK Motors Program—Searching an

Array (cont’d.)

Page 564: c++Programming

An Introduction to Programming with C++, Seventh Edition 47

Figure 11-26 JK motors program (cont’d.)

The JK Motors Program—Searching an

Array (cont’d.)

Page 565: c++Programming

The JK Motors Program—Searching an

Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 48

Figure 11-27 Sample run of the JK motors program

Page 566: c++Programming

• Program uses a six-element array to store hourly rates, each associated with a specific pay code

• Program prompts user to enter a pay code and determines whether the pay code is valid

• Pay code must be between 1 and 6, inclusive

• If pay code is valid, program uses pay code to display appropriate hourly rate from array

• If the pay code is not valid, program displays the message “Invalid pay code”

The Hourly Rate Program—Accessing

an Individual Element

An Introduction to Programming with C++, Seventh Edition 49

Page 567: c++Programming

An Introduction to Programming with C++, Seventh Edition 50

Figure 11-28 Problem specification, IPO chart information,

and C++ instructions for the hourly rate program

The Hourly Rate Program—Accessing

an Individual Element (cont’d.)

Page 568: c++Programming

The Hourly Rate Program—Accessing

an Individual Element (cont’d.)

An Introduction to Programming with C++, Seventh Edition 51

Figure 11-28 Problem specification, IPO chart information,

and C++ instructions for the hourly rate program (cont’d.)

Page 569: c++Programming

An Introduction to Programming with C++, Seventh Edition 52

Figure 11-29 Hourly rate program

The Hourly Rate Program—Accessing

an Individual Element (cont’d.)

Page 570: c++Programming

The Hourly Rate Program—Accessing

an Individual Element (cont’d.)

An Introduction to Programming with C++, Seventh Edition 53

Figure 11-30 Sample run of the hourly rate program

Page 571: c++Programming

• Program’s main function assigns random numbers between 1 and 100 to a five-element int array named randNums

• Calls a program-defined void function to display contents of array

• Then calls a program-defined value-returning function to determine highest number in array

• main function then display’s highest value

The Random Numbers Program—

Finding the Highest Value

An Introduction to Programming with C++, Seventh Edition 54

Page 572: c++Programming

An Introduction to Programming with C++, Seventh Edition 55

Figure 11-31 Problem specification, IPO chart information,

and C++ instructions for the random numbers program

The Random Numbers Program

(cont’d.)

Page 573: c++Programming

An Introduction to Programming with C++, Seventh Edition 56

Figure 11-31 Problem specification, IPO chart information, and

C++ instructions for the random numbers program (cont’d.)

The Random Numbers Program

(cont’d.)

Page 574: c++Programming

An Introduction to Programming with C++, Seventh Edition 57

Figure 11-31 Problem specification, IPO chart information, and

C++ instructions for the random numbers program (cont’d.)

The Random Numbers Program

(cont’d.)

Page 575: c++Programming

An Introduction to Programming with C++, Seventh Edition 58

Figure 11-31 Problem specification, IPO chart information, and

C++ instructions for the random numbers program (cont’d.)

The Random Numbers Program

(cont’d.)

Page 576: c++Programming

The Random Numbers Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 59

Figure 11-32 Sample run of the random numbers program

Page 577: c++Programming

An Introduction to Programming with C++, Seventh Edition 60

Figure 11-33 Random numbers program

The Random Numbers Program

(cont’d.)

Page 578: c++Programming

An Introduction to Programming with C++, Seventh Edition 61

Figure 11-33 Random numbers program (cont’d.)

The Random Numbers Program

(cont’d.)

Page 579: c++Programming

The Random Numbers Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 62

Figure 11-33 Random numbers program (cont’d.)

Page 580: c++Programming

The Random Numbers Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 63

Figure 11-34 Desk-check table after the for loop on lines 24 through 26 ends

Page 581: c++Programming

The Random Numbers Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 64

Figure 11-35 Desk-check table after the displayArray function header is processed

Page 582: c++Programming

The Random Numbers Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 65

Figure 11-36 Desk-check table after the displayArray function ends

Page 583: c++Programming

The Random Numbers Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 66

Figure 11-37 Desk-check table after the declaration

statements on lines 52 and 55 are processed

Page 584: c++Programming

The Random Numbers Program

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 67

Figure 11-38 Desk-check table showing the fourth element’s value entered in the high variable

Page 585: c++Programming

An Introduction to Programming with C++, Seventh Edition 68

Figure 11-39 Completed desk-check table for random numbers program

The Random Numbers Program

(cont’d.)

Page 586: c++Programming

• You sometimes need to arrange the contents of an array in either ascending or descending order

• Arranging data in a specific order is called sorting

• When a one-dimensional array is sorted in ascending order, first element contains smallest value and last element contains largest value

• Conversely, when sorted in descending order, first element contains largest value and last element contains smallest value

Sorting the Data Stored in a One-

Dimensional Array

An Introduction to Programming with C++, Seventh Edition 69

Page 587: c++Programming

• Many different types of sorting algorithms

• Bubble sort provides a quick and easy way to sort items stored in an array, as long as the number of items is relatively small (e.g., fewer than 50)

• Works by comparing adjacent array elements and swapping ones that are out of order

• Continues comparing and swapping until data in the array are sorted

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 70

Page 588: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 71

Figure 11-40 Array values before, during, and after the bubble sort

Page 589: c++Programming

An Introduction to Programming with C++, Seventh Edition 72

Figure 11-41 Bubble sort program

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

Page 590: c++Programming

An Introduction to Programming with C++, Seventh Edition 73

Figure 11-41 Bubble sort program (cont’d.)

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

Page 591: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 74

Figure 11-42 Desk-check table after the declaration

statements on lines 11 through 16 are processed

Page 592: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 75

Figure 11-43 Desk-check table after nested loop is processed first time

Page 593: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 76

Figure 11-44 Desk-check table after nested loop is processed second time

Page 594: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 77

Figure 11-45 Desk-check table after nested loop is processed third time

Page 595: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 78

Figure 11-46 Desk-check table after outer loop is processed first time

Page 596: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 79

Figure 11-47 Desk-check table after the instructions

on lines 21 and 23 are processed

Page 597: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 80

Figure 11-48 Desk-check table after the instructions

in the nested loop are processed

Page 598: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 81

Figure 11-49 Desk-check table after the instructions

in the nested loop are processed again

Page 599: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 82

Figure 11-50 Current status of the desk-check table

Page 600: c++Programming

Sorting the Data Stored in a One-

Dimensional Array (cont’d.)

An Introduction to Programming with C++, Seventh Edition 83

Figure 11-51 Result of running the bubble sort program

Page 601: c++Programming

• Program for a motorcycle club displays annual fee associated with membership type entered by user

• Program uses two parallel one-dimensional arrays

– char array named types: stores the five membership types

– int array named fees: stores annual fee associated with each type

• Two arrays are referred to as parallel arrays if their elements are related by their position in the arrays

Parallel One-Dimensional Arrays

An Introduction to Programming with C++, Seventh Edition 84

Page 602: c++Programming

An Introduction to Programming with C++, Seventh Edition 85

Figure 11-52 Problem specification and IPO chart

information for the club membership program

Parallel One-Dimensional Arrays

(cont’d.)

Page 603: c++Programming

An Introduction to Programming with C++, Seventh Edition 86

Figure 11-52 Problem specification and IPO chart

information for the club membership program (cont.)

Parallel One-Dimensional Arrays

(cont’d.)

Page 604: c++Programming

An Introduction to Programming with C++, Seventh Edition 87

Figure 11-53 IPO chart information and C++ instructions

for the club membership program

Parallel One-Dimensional Arrays

(cont’d.)

Page 605: c++Programming

An Introduction to Programming with C++, Seventh Edition 88

Figure 11-53 IPO chart information and C++ instructions

for the club membership program (cont.)

Parallel One-Dimensional Arrays

(cont’d.)

Page 606: c++Programming

An Introduction to Programming with C++, Seventh Edition 89

Figure 11-54 Club membership program

Parallel One-Dimensional Arrays

(cont’d.)

Page 607: c++Programming

Parallel One-Dimensional Arrays

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 90

Figure 11-54 Club membership program (cont’d.)

Page 608: c++Programming

Parallel One-Dimensional Arrays

(cont’d.)

An Introduction to Programming with C++, Seventh Edition 91

Figure 11-55 Sample run of the club membership program

Page 609: c++Programming

• An array is a group of variables that have the same name and data type

• One- and two-dimensional arrays are the most common types

• Arrays are often used to store related data in internal memory: more efficient to access than from disk

• Must declare an array before using it

• After declaration, you can use an assignment statement or extraction operator to enter data into it

Summary

An Introduction to Programming with C++, Seventh Edition 92

Page 610: c++Programming

• Each element of a one-dimensional array is assigned a unique number, called a subscript

• First element is assigned a subscript of 0, second a subscript of 1, and so on

• Last subscript of a one-dimensional array is always one number less than the number of elements

• You refer to an element by the array’s name followed by the subscript in square brackets

• Parallel arrays are two or more arrays whose elements are related by their position in the arrays

Summary (cont’d.)

An Introduction to Programming with C++, Seventh Edition 93

Page 611: c++Programming

• Study the code in Figure 11-56 and then answer the questions

• The domestic array contains the amounts the company sold domestically during the months January through June

• The international array contains the amounts the company sold internationally during the same period

Lab 11-1: Stop and Analyze

An Introduction to Programming with C++, Seventh Edition 94

Page 612: c++Programming

• Plan and create a program for Penelope Havert

Lab 11-2: Plan and Create

An Introduction to Programming with C++, Seventh Edition 95

Figure 11-57 Problem specification for Lab 11-2

Page 613: c++Programming

• Modify the program in Lab 11-2

• Change the void displayTotal function with a value-returning function named getTotal

– Function should calculate total rainfall and return value to main function to be displayed

• main function should display an error message when user enters a menu choice other than 1, 2, or 3 and should then display the menu again

• Test the program appropriately

Lab 11-3: Modify

An Introduction to Programming with C++, Seventh Edition 96

Page 614: c++Programming

• Desk-check the code in Figure 11-60 using the data shown below

• What will the for loop on Lines 31 through 34 display on the screen?

Lab 11-4: Desk-Check

An Introduction to Programming with C++, Seventh Edition 97

Page 615: c++Programming

• Open the program in the Lab11-5.cpp file

• Debug the program

Lab 11-5: Debug

An Introduction to Programming with C++, Seventh Edition 98