c++programming
DESCRIPTION
Programming with C++TRANSCRIPT
Introduction to Programming in C++
Seventh Edition
Chapter 1:
An Introduction to 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
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
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
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
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
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
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
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
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
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
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.
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
The Sequence Structure (cont.)
An Introduction to Programming with C++, Seventh Edition 14
Figure 1-1 An example of the sequence structure
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
The Selection Structure (cont.)
An Introduction to Programming with C++, Seventh Edition 16
Figure 1-2 An example of the selection structure
An Introduction to Programming with C++, Seventh Edition 17
The Selection Structure (cont.)
Figure 1-3 Another example of the selection structure
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
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
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?
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
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
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
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
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
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
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
Introduction to Programming in C++
Seventh Edition
Chapter 2:
Beginning the Problem-Solving Process
• 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
• 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
• 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
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
Solving Everyday Problems (cont’d.)
Figure 2-2 Modified algorithm for the bill paying problem
6 An Introduction to Programming with C++, Seventh Edition
• 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
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
• 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
Step 1−Analyzing the Problem (cont’d.)
Figure 2-4 Problem specification for Treyson Mobley
10 An Introduction to Programming with C++, Seventh Edition
• 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
• 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
• 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
• 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
• 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
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
• 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
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.)
• 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
• 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
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
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
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
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
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
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.)
• 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
The Gas Mileage Problem
Figure 2-21 Problem specification for the gas mileage problem
28 An Introduction to Programming with C++, Seventh Edition
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
• 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
• 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
• 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
• 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
• 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
• 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
• 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
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 3:
Variables and Constants
• 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
• 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
• 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
• 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
• 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
An Introduction to Programming with C++, Seventh Edition
Internal Memory (cont’d.)
Figure 3-1 Illustration of storage bins
7
• 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
• 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
• 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
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.)
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
• 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
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
• 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
• 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
• 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
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
• 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
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
• 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
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
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
An Introduction to Programming with C++, Seventh Edition
Figure 3-9 Partial ASCII chart
24
How Data Is Stored in Internal Memory
(cont’d.)
• 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
• 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
• 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
• 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
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
• 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
• 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
• 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
• 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
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
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
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
• 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
• 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
• 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
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
An Introduction to Programming with C++, Seventh Edition
Lab 3-2: Plan and Create
Figure 3-15 Problem specification for Lab 3-2
41
• 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
• 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
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 4:
Completing the Problem-Solving Process
• 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
• 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
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.)
• 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
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
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
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.)
• 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
• 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
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
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.)
• 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
• 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
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.)
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.)
• 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
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.)
• 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
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.)
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.)
• 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
• 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
An Introduction to Programming with C++, Seventh Edition
Assignment Statements (cont’d.)
Figure 4-11 How to write an assignment statement
24
An Introduction to Programming with C++, Seventh Edition
Assignment Statements (cont’d.)
Figure 4-11 How to write an assignment statement (cont’d.)
25
An Introduction to Programming with C++, Seventh Edition
Figure 4-12 Calculation statements
for the Treyson Mobley problem
26
Assignment Statements (cont’d.)
• 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
An Introduction to Programming with C++, Seventh Edition 28
Figure 4-13 How to use an arithmetic assignment operator
Arithmetic Assignment Operators (cont’d)
• 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
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
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
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
• 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
• 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
• 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
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
• 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
• 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
• 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
• 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
An Introduction to Programming with C++, Seventh Edition
Step 6–Evaluate and Modify the Program
(cont’d.)
Figure 4-21 Treyson Mobley program
41
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
An Introduction to Programming with C++, Seventh Edition
Step 6–Evaluate and Modify the Program
(cont’d.)
Figure 4-22 Command Prompt window
43
• 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
• 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
• 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
• 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
• 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
• 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
An Introduction to Programming with C++, Seventh Edition
Lab 4-1: Stop and Analyze
Figure 4-23 Examples for Lab 4-1
50
• 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
• 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
• 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
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 5:
The Selection Structure
• 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
• 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
• 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
Making Decisions (cont’d.)
An Introduction to Programming with C++, Seventh Edition 5
Figure 5-1 A problem that requires
the sequence structure only
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
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
• 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
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
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
• 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
• 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
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.)
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.)
• 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
• 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
• 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
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
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
• 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
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.)
Swapping Numeric Values (cont’d.)
An Introduction to Programming with C++, Seventh Edition 22
Figure 5-10 Illustration of the swapping concept
Swapping Numeric Values (cont’d.)
An Introduction to Programming with C++, Seventh Edition 23
Figure 5-11 Flowchart for the swapping program
Swapping Numeric Values (cont’d.)
An Introduction to Programming with C++, Seventh Edition 24
Figure 5-12 Sample run of the swapping program
• 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
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
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.)
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.)
• 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
• 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
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
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)
Logical Operators (cont’d.)
An Introduction to Programming with C++, Seventh Edition 33
Figure 5-17 Truth tables for the logical operators
• 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
• 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
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
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
• 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
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)
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
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
• 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
• 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
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.)
• 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
• 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
• 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
• 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
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
Formatting Numeric Output (cont’d.)
An Introduction to Programming with C++, Seventh Edition 50
Figure 5-27 How to use the setprecision stream manipulator
• 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
• 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
• 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
• 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
• 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
Lab 5-1: Stop and Analyze
An Introduction to Programming with C++, Seventh Edition 56
Figure 5-28 Program for Lab 5-1
• 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
• 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
• 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
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 6:
More on the Selection Structure
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 4
Figure 6-1 Problem that requires a selection structure
Making Decisions (cont’d.)
Making Decisions (cont’d.)
An Introduction to Programming with C++, Seventh Edition 5
Figure 6-2 Problem that requires a nested selection structure
Making Decisions (cont’d.)
An Introduction to Programming with C++, Seventh Edition 6
Figure 6-3 Problem that requires two nested selection structures
• 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
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
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.)
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.)
• 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
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
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.)
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.)
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.)
• 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
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
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.)
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.)
• 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
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
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.)
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
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
• 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
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
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
• 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
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
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
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
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.)
• 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
• 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
• 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
• 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
The switch Statement (cont’d.)
An Introduction to Programming with C++, Seventh Edition 37
Figure 6-28 How to use the switch statement
An Introduction to Programming with C++, Seventh Edition 38
Example similar to code in Figure 6-28
The switch Statement (cont’d.)
The switch Statement (cont’d.)
An Introduction to Programming with C++, Seventh Edition 39
Figure 6-29 Problem specification for the Warren Company problem
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.)
The switch Statement (cont’d.)
An Introduction to Programming with C++, Seventh Edition 41
Figure 6-30 Flowchart for the Warren Company problem
• 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
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 45
Figure 6-31 Flowchart for Lab 6-1
Lab 6-1: Stop and Analyze
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
• 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
An Introduction to Programming with C++, Seventh Edition 48
Figure 6-39 Code for Lab 6-4
Lab 6-4: Desk-Check
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 7:
The Repetition Structure
• 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
• 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
• 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
• 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
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
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
• 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
• 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
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
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.)
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
• 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
• 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
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
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
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
• 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
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 21
Figure 7-13 How to use the while statement
The while Statement (cont’d.)
An Introduction to Programming with C++, Seventh Edition 22
An alternate example using the while statement
The while Statement (cont’d.)
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.)
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
• 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
• 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
• 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
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
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.)
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)
The Sales Express Program (cont’d.)
An Introduction to Programming with C++, Seventh Edition 31
Figure 7-18 Flowchart for the Sales Express program
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
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
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
• 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
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
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.)
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.)
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.)
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.)
• 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
• 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
• 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
The for Statement (cont’d.)
An Introduction to Programming with C++, Seventh Edition 44
Figure 7-32 How to use the for statement
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.)
• 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
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.)
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
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
• 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
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.)
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
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.)
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
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
• 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
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.)
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.)
• 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
• 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
• 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
• 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
• 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
Lab 7-2: Plan and Create
An Introduction to Programming with C++, Seventh Edition 64
Figure 7-47 Problem specification for Lab 7-2
• 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
• 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
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 8: More on the Repetition Structure
• 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
• 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
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.)
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
• 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
An Introduction to Programming with C++, Seventh Edition 7
Figure 8-3 Wheels & More problem specification & algorithms (continues)
Flowcharting a Posttest Loop
(cont’d.)
An Introduction to Programming with C++, Seventh Edition 8
Figure 8-3 Wheels & More problem
specification & algorithms (continued)
Flowcharting a Posttest Loop
(cont’d.)
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
• 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
• 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
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.)
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.)
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.)
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.)
• 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
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
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
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
• 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
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
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.)
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
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
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.)
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
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
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
The Asterisks Program (cont’d.)
An Introduction to Programming with C++, Seventh Edition 29
Figure 8-24 Sample run of the modified asterisks program
• 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
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
An Introduction to Programming with C++, Seventh Edition 32
Figure 8-26 Flowchart for the savings calculator program
The Savings Calculator Program
(cont’d.)
• 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
An Introduction to Programming with C++, Seventh Edition 34
Figure 8-27 How to use the pow function
The pow Function (cont’d.)
• 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
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 38
Figure 8-29 Savings calculator program
Coding the Savings Calculator
Program (cont’d.)
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
• 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
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
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 44
Figure 8-33 Modified savings calculator program
Modifying the Savings Calculator
Program (cont’d.)
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
• 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
• 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
• 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
Lab 8-2: Plan and Create
An Introduction to Programming with C++, Seventh Edition 49
Figure 8-37 Problem specification for Lab 8-2
• 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
• 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
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 9: Value-Returning Functions
• 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
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 5
Figure 9-1 Illustrations of value-returning and void functions
Functions (cont’d.)
• 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
• 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
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.)
An Introduction to Programming with C++, Seventh Edition 9
Figure 9-3 Flowchart of the hypotenuse program
The Hypotenuse Program (cont’d.)
• 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
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 13
Figure 9-6 Hypotenuse program
Finding the Square Root of a Number
(cont’d.)
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
• 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
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
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.)
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.)
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 21
Figure 9-10 How to use the rand function
Generating Random Integers
(cont’d.)
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.)
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.)
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 26
Figure 9-12 How to use the srand function
Generating Random Integers
(cont’d.)
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 29
Figure 9-14 Random addition problems program
Generating Random Integers
(cont’d.)
An Introduction to Programming with C++, Seventh Edition 30
Figure 9-14 Random addition problems program (cont’d.)
Generating Random Integers
(cont’d.)
An Introduction to Programming with C++, Seventh Edition 31
Figure 9-15 Sample run of random addition problems program
Generating Random Integers
(cont’d.)
• 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
• 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
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.)
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.)
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.)
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.)
• 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
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 41
Figure 9-18 How to call a function
Calling a Function (cont’d.)
An Introduction to Programming with C++, Seventh Edition 42
Figure 9-18 How to call a function (cont’d.)
Calling a Function (cont’d.)
An Introduction to Programming with C++, Seventh Edition 43
Figure 9-19 Function calls and function definitions
Calling a Function (cont’d.)
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.)
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.)
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.)
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.)
• 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
An Introduction to Programming with C++, Seventh Edition 49
Figure 9-21 How to write a function prototype
Function Prototypes (cont’d.)
An Introduction to Programming with C++, Seventh Edition 50
Figure 9-22 Modified random addition problems program
Function Prototypes (cont’d.)
An Introduction to Programming with C++, Seventh Edition 51
Figure 9-22 Modified random addition problems program (cont’d.)
Function Prototypes (cont’d.)
• 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
An Introduction to Programming with C++, Seventh Edition 53
Figure 9-23 Western Elementary School program
The Western Elementary School
Program (cont’d.)
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.)
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.)
• 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
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.)
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 60
Figure 9-27 Area calculator program
The Area Calculator Program
(cont’d.)
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.)
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.)
• 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
• 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
• 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
• 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
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.)
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 70
Figure 9-35 Bonus calculator program
The Bonus Calculator Program
(cont’d.)
An Introduction to Programming with C++, Seventh Edition 71
Figure 9-35 Bonus calculator program (cont’d.)
The Bonus Calculator Program
(cont’d.)
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.)
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.)
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.)
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.)
• 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
• 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
• 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
• 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
• 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
• 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
Lab 9-2: Plan and Create
An Introduction to Programming with C++, Seventh Edition 82
Figure 9-44 Problem specification for Lab 9-2
• 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
• 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
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 10: Void Functions
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 4
Figure 10-1 Illustration of value-returning and void functions
Functions (cont’d.)
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
• 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
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.)
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.)
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.)
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 12
Figure 10-5 ABC Company program
Creating Program-Defined Void
Functions (cont’d.)
An Introduction to Programming with C++, Seventh Edition 13
Figure 10-5 ABC Company program (cont’d.)
Creating Program-Defined Void
Functions (cont’d.)
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.)
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 17
Figure 10-8 Age message program
Reviewing Passing Variables by Value
(cont’d.)
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.)
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.)
• 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
• 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
An Introduction to Programming with C++, Seventh Edition 22
Figure 10-13 Modified age message program
Passing Variables by Reference
(cont’d.)
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.)
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.)
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.)
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.)
• 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
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
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.)
An Introduction to Programming with C++, Seventh Edition 30
Figure 10-23 Salary program
The Salary Program (cont’d.)
An Introduction to Programming with C++, Seventh Edition 31
Figure 10-23 Salary program (cont’d.)
The Salary Program (cont’d.)
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 34
Figure 10-28 Sample run of the salary program
The Salary Program (cont’d.)
• 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
• 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
• 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
• 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
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
• 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
• 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
• 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
Introduction to Programming in C++
Seventh Edition
Chapter 11: One-Dimensional Arrays
• 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
• 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
• 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
• 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
• 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
• 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
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.)
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.)
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
• 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
• 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
• 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
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.)
• 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
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.)
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.)
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
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.)
• 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
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
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.)
• 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
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.)
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.)
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
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
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
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.)
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.)
• 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
• 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
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.)
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.)
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.)
• 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
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.)
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 40
Figure 11-23 Moonbucks Coffee program
The Moonbucks Coffee Program
(cont’d.)
An Introduction to Programming with C++, Seventh Edition 41
Figure 11-23 Moonbucks Coffee program (cont’d.)
The Moonbucks Coffee Program
(cont’d.)
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
• 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
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 46
Figure 11-26 JK motors program
The JK Motors Program—Searching an
Array (cont’d.)
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.)
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
• 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
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.)
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.)
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.)
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
• 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
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.)
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.)
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.)
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.)
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
An Introduction to Programming with C++, Seventh Edition 60
Figure 11-33 Random numbers program
The Random Numbers Program
(cont’d.)
An Introduction to Programming with C++, Seventh Edition 61
Figure 11-33 Random numbers program (cont’d.)
The Random Numbers Program
(cont’d.)
The Random Numbers Program
(cont’d.)
An Introduction to Programming with C++, Seventh Edition 62
Figure 11-33 Random numbers program (cont’d.)
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
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
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
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
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
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.)
• 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
• 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
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
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.)
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.)
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
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
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
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
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
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
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
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
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
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
• 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
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.)
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.)
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.)
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.)
An Introduction to Programming with C++, Seventh Edition 89
Figure 11-54 Club membership program
Parallel One-Dimensional Arrays
(cont’d.)
Parallel One-Dimensional Arrays
(cont’d.)
An Introduction to Programming with C++, Seventh Edition 90
Figure 11-54 Club membership program (cont’d.)
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
• 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
• 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
• 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
• 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
• 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
• 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
• 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