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
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
The Programmers 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
What Traits Should a Software Developer Possess?
Analytical skills Communication skills Creativity Customer-service skills Detail oriented Problem-solving skills Teamwork Technical skills
An Introduction to Programming with C++, Seventh Edition
Employment Opportunities
Computer software engineer: designs an appropriate solution to a users 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
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
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 errorprone; requires highly trained programmers
An Introduction to Programming with C++, Seventh Edition 8
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
High-Level Languages
High-level languages allow programmers to use Englishlike 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
10
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 11
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
12
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
An Introduction to Programming with C++, Seventh Edition
13
The Sequence Structure (cont.)
Figure 1-1 An example of the sequence structure
An Introduction to Programming with C++, Seventh Edition 14
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
An Introduction to Programming with C++, Seventh Edition
15
The Selection Structure (cont.)
Figure 1-2 An example of the selection structure
An Introduction to Programming with C++, Seventh Edition
16
The Selection Structure (cont.)
Figure 1-3 Another example of the selection structure
An Introduction to Programming with C++, Seventh Edition 17
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
An Introduction to Programming with C++, Seventh Edition
18
The Repetition Structure (cont.)
Figure 1-4 Original algorithm and modified algorithm showing the repetition structure
An Introduction to Programming with C++, Seventh Edition 19
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?
An Introduction to Programming with C++, Seventh Edition
20
The Repetition Structure (cont.)
Figure 1-5 Algorithm showing the modified condition in the repetition structure
An Introduction to Programming with C++, Seventh Edition
21
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 procedureoriented 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 salespersons sales Your task is to create a program that calculates the amount of each salespersons bonus The program should print each salespersons name and bonus amount
An Introduction to Programming with C++, Seventh Edition
25
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
26
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
An Introduction to Programming with C++, Seventh Edition
27
Introduction to Programming in C++ Seventh Edition
Chapter 2: Beginning the Problem-Solving Process
Chapter Objectives
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
An Introduction to Programming with C++, Seventh Edition
Problem Solving
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)
An Introduction to Programming with C++, Seventh Edition
Solving Everyday Problems
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
An Introduction to Programming with C++, Seventh Edition
Solving Everyday Problems (contd.)
Figure 2-1 Summary of the analysis and planning steps for the bill paying problem
An Introduction to Programming with C++, Seventh Edition 5
Solving Everyday Problems (contd.)
Figure 2-2 Modified algorithm for the bill paying problem
An Introduction to Programming with C++, Seventh Edition 6
Creating Computer Solutions to Problems
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
An Introduction to Programming with C++, Seventh Edition
Creating Computer Solutions to Problems (contd.)
Figure 2-3 How to create a computer solution to a problem
An Introduction to Programming with C++, Seventh Edition
Step 1Analyzing the Problem
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
An Introduction to Programming with C++, Seventh Edition
Step 1Analyzing the Problem (contd.)
Figure 2-4 Problem specification for Treyson Mobley
An Introduction to Programming with C++, Seventh Edition
10
Step 1Analyzing the Problem (contd.)
Some programmers use an IPO chart to organize and summarize the results of a problem analysis
IPO: Input, processing, and output
Figure 2-5 Partially completed IPO chart showing the input and output items
An Introduction to Programming with C++, Seventh Edition
11
Hints for Analyzing Problems
Several readings of the problem may be necessary to fully understand the problem Cross out irrelevant information in the problem description
Figure 2-6 Problem specification with unimportant information crossed out
An Introduction to Programming with C++, Seventh Edition
12
Hints for Analyzing Problems (contd.)
Some problem specifications contain incomplete information
Figure 2-7 Problem specification that does not contain enough information
An Introduction to Programming with C++, Seventh Edition
13
Hints for Analyzing Problems (contd.)
Distinguish between information that is missing and information that is implied
Figure 2-8 Problem specification in which the input is not explicitly stated
An Introduction to Programming with C++, Seventh Edition
14
Step 2Planning the Algorithm
Algorithm: set of instructions that will transform the problems 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
An Introduction to Programming with C++, Seventh Edition
15
Step 2Planning the Algorithm (contd.)
Figure 2-9 Problem specification and IPO chart for the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition 16
Step 2Planning the Algorithm (contd.)
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
An Introduction to Programming with C++, Seventh Edition
17
Step 2Planning the Algorithm (contd.)
Figure 2-10 Figure 2-9s algorithm in flowchart form
An Introduction to Programming with C++, Seventh Edition 18
Step 2Planning the Algorithm (contd.)
A problem can have more than one solution
Figure 2-11 A different solution to the Treyson Mobley problem (pseudocode)
An Introduction to Programming with C++, Seventh Edition 19
Step 2Planning the Algorithm (contd.)
Processing item: an intermediate value (neither input nor output) the algorithm uses to transform input into output
Figure 2-11 A different solution to the Treyson Mobley problem (flowchart)
An Introduction to Programming with C++, Seventh Edition 20
Step 3Desk-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
An Introduction to Programming with C++, Seventh Edition
21
Step 3Desk-Checking the Algorithm (contd.)
Figure 2-12 Manual tip calculation for the first desk-check
An Introduction to Programming with C++, Seventh Edition
22
Step 3Desk-Checking the Algorithm (contd.)
Figure 2-13 Treyson Mobley solution and partially completed desk-check table
An Introduction to Programming with C++, Seventh Edition
23
Step 3Desk-Checking the Algorithm (contd.)
Figure 2-14 Input values entered in the desk-check table
Figure 2-15 Processing items value entered in the desk-check table
Figure 2-16 Output value entered in the desk-check table
An Introduction to Programming with C++, Seventh Edition 24
Step 3Desk-Checking the Algorithm (contd.)
Figure 2-17 Manual tip calculation for the second desk-check
An Introduction to Programming with C++, Seventh Edition
25
Step 3Desk-Checking the Algorithm (contd.)
Figure 2-18 Second set of input values entered in the desk-check table
Figure 2-19 Value of the second desk-checks processing item entered in the desk-check table
Figure 2-20 Value of the second desk-checks output item entered in the desk-check table
An Introduction to Programming with C++, Seventh Edition 26
Step 3Desk-Checking the Algorithm (contd.)
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
An Introduction to Programming with C++, Seventh Edition
27
The Gas Mileage Problem
Figure 2-21 Problem specification for the gas mileage problem
An Introduction to Programming with C++, Seventh Edition
28
The Gas Mileage Problem (contd.)
Plan the algorithm with an IPO chart
Figure 2-22 IPO chart for the gas mileage problem
An Introduction to Programming with C++, Seventh Edition
29
The Gas Mileage Problem (contd.)
Then desk-check the algorithm
Figure 2-23 Desk-check table for the gas mileage problem
An Introduction to Programming with C++, Seventh Edition
30
Summary
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
An Introduction to Programming with C++, Seventh Edition
31
Summary (contd.)
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
An Introduction to Programming with C++, Seventh Edition
32
Lab 2-1: Stop and Analyze
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
Figure 2-26 IPO chart for Lab 2-1
An Introduction to Programming with C++, Seventh Edition 33
Lab 2-2: Plan and Create
Create an algorithm for the manager of the Lakeview Hotel
Figure 2-30 Completed IPO chart for Lab 2-2
An Introduction to Programming with C++, Seventh Edition 34
Lab 2-3: Modify
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
An Introduction to Programming with C++, Seventh Edition
35
Lab 2-4: Desk-Check
An algorithm is given to calculate and display an annual property tax Desk-check the algorithm three times using the given values
Figure 2-36 IPO chart for Lab 2-4
An Introduction to Programming with C++, Seventh Edition 36
Lab 2-5: Debug
An algorithm is given to calculate and display the average of three numbers but is incorrect Find and correct the errors in the algorithm
Figure 2-37 IPO chart for Lab 2-5
Figure 2-42 Corrected algorithm for Lab 2-5
An Introduction to Programming with C++, Seventh Edition 37
Introduction to Programming in C++ Seventh Edition
Chapter 3: Variables and Constants
Chapter Objectives
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
Beginning Step 4 in the Problem-Solving Process
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 computers internal memory
An Introduction to Programming with C++, Seventh Edition
Internal Memory
Computers 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 (contd.)
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 (contd.)
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 (contd.)
Figure 3-1 Illustration of storage bins
An Introduction to Programming with C++, Seventh Edition 7
Selecting a Name for a Memory Location
Name (identifier) assigned to a memory location should be descriptive Should help the programmer/other programmers remember/understand the memory locations 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 (contd.)
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 (contd.)
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 10
Selecting a Name for a Memory Location (contd.)
Figure 3-2 How to name a memory location in C++
An Introduction to Programming with C++, Seventh Edition 11
Revisiting the Treyson Mobley Problem
Figure 3-3 Problem specification, IPO chart, and desk-check table from Chapter 2
An Introduction to Programming with C++, Seventh Edition 12
Revisiting the Treyson Mobley Problem (contd.)
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
13
Revisiting the Treyson Mobley Problem (contd.)
Figure 3-4 Names of the variables for the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition
14
Selecting a Data Type for a Memory Location
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
15
Selecting a Data Type for a Memory Location (contd.)
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 16
Selecting a Data Type for a Memory Location (contd.)
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 17
Selecting a Data Type for a Memory Location (contd.)
Figure 3-5 Most commonly used data types in C++
An Introduction to Programming with C++, Seventh Edition 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
Selecting a Data Type for a Memory Location (contd.)
Figure 3-6 Data type assigned to each variable for the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition
20
How Data Is Stored in Internal Memory
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 21
How Data Is Stored in Internal Memory (contd.)
Figure 3-7 How to use the decimal (base 10) number system
An Introduction to Programming with C++, Seventh Edition
22
How Data Is Stored in Internal Memory (contd.)
Figure 3-8 How to use the binary (base 2) number system
An Introduction to Programming with C++, Seventh Edition
23
How Data Is Stored in Internal Memory (contd.)
Figure 3-9 Partial ASCII chart
An Introduction to Programming with C++, Seventh Edition 24
Selecting an Initial Value for a Memory Location
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
25
Selecting an Initial Value for a Memory Location (contd.)
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 26
Selecting an Initial Value for a Memory Location (contd.)
Before assigning initial value to a memory location, computer checks that values data type matches locations data type If they dont 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 27
Selecting an Initial Value for a Memory Location (contd.)
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
28
An Introduction to Programming with C++, Seventh Edition
Selecting an Initial Value for a Memory Location (contd.)
Figure 3-10 Initial values for the variables in the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition
29
Declaring a Memory Location
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
30
Declaring a Memory Location (contd.)
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 31
Declaring a Memory Location (contd.)
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
32
Declaring a Memory Location (contd.)
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 constants 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 33
Declaring a Memory Location (contd.)
Figure 3-11 How to declare a variable in C++
An Introduction to Programming with C++, Seventh Edition
34
Declaring a Memory Location (contd.)
Figure 3-12 C++ declaration statements for the variables in the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition
35
Declaring a Memory Location (contd.)
Figure 3-13 How to declare a named constant in C++
An Introduction to Programming with C++, Seventh Edition
36
Summary
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 computers internal memory using binary number system Memory locations store one item at a time Memory locations data type determines how a value is stored and interpreted when retrieved
An Introduction to Programming with C++, Seventh Edition
37
Summary (contd.)
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
38
Summary (contd.)
Data type of literal constant assigned to memory location should be same as memory locations type If types dont match, implicit type conversion is used to either promote or demote so they match Promoting doesnt 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 39
Lab 3-1: Stop and Analyze
Figure 3-14 Problem specification, IPO chart, and desk-check table for Lab 3-1
An Introduction to Programming with C++, Seventh Edition 40
Lab 3-2: Plan and Create
Figure 3-15 Problem specification for Lab 3-2
An Introduction to Programming with C++, Seventh Edition
41
Lab 3-3: Modify
Modify the IPO chart in Figure 3-17 so that it includes the radius squared as a processing item
Figure 3-17 Completed IPO chart for Lab 3-2
An Introduction to Programming with C++, Seventh Edition
42
Lab 3-4: Desk-Check
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
Figure 3-18 Manual area calculations for the two desk-checks
Figure 3-19 Completed desk-check table for Lab 3-2
An Introduction to Programming with C++, Seventh Edition 43
Lab 3-5: Debug
Correct the C++ instructions shown in Figure 3-21
The memory locations will store real numbers
Find and correct the errors in the algorithm
Figure 3-21 IPO chart information and C++ instructions for Lab 3-5
An Introduction to Programming with C++, Seventh Edition 44
Introduction to Programming in C++ Seventh Edition
Chapter 4: Completing the Problem-Solving Process
Objectives
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
Finishing Step 4 in the Problem-Solving Process
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 (contd.)
Figure 4-1 Problem specification, IPO chart information, and variable declaration
An Introduction to Programming with C++, Seventh Edition 4
Getting Data from the Keyboard
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 (contd.)
Figure 4-2 Relationship among the keyboard, cin object, extraction operator, and internal memory
An Introduction to Programming with C++, Seventh Edition
Getting Data from the Keyboard (contd.)
Figure 4-3 How to use cin and >> to get numeric or character data
An Introduction to Programming with C++, Seventh Edition 7
Getting Data from the Keyboard (contd.)
Figure 4-4 Input statements for the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition 8
Displaying Messages on the Computer Screen
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 (contd.)
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
10
Displaying Messages on the Computer Screen (contd.)
Figure 4-5 How to use the cout object
An Introduction to Programming with C++, Seventh Edition
11
Displaying Messages on the Computer Screen (contd.)
Figure 4-6 Prompts and output statement for the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition 12
Arithmetic Operators in C++
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
13
Arithmetic Operators in C++ (contd.)
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
14
Arithmetic Operators in C++ (contd.)
Figure 4-7 Standard arithmetic operators and their order of precedence
An Introduction to Programming with C++, Seventh Edition
15
Arithmetic Operators in C++ (contd.)
Figure 4-8 Expressions containing more than one operator having the same precedence
An Introduction to Programming with C++, Seventh Edition
16
Type Conversions in Arithmetic Expressions
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 17
Type Conversions in Arithmetic Expressions (contd.)
Figure 4-9 Examples of expressions that require implicit type conversions
An Introduction to Programming with C++, Seventh Edition
18
The static_cast Operator
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
19
The static_cast Operator (contd.)
Figure 4-10 How to use the static_cast operator
An Introduction to Programming with C++, Seventh Edition 20
The static_cast Operator (contd.)
Figure 4-10 How to use the static_cast operator (contd.)
An Introduction to Programming with C++, Seventh Edition 21
Assignment Statements
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
22
Assignment Statements (contd.)
Data type of expression in an assignment statement must match data type of the variable If they dont match, compiler will use implicit type casting to get them to match
Doesnt 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 23
Assignment Statements (contd.)
Figure 4-11 How to write an assignment statement
An Introduction to Programming with C++, Seventh Edition 24
Assignment Statements (contd.)
Figure 4-11 How to write an assignment statement (contd.)
An Introduction to Programming with C++, Seventh Edition 25
Assignment Statements (contd.)
Figure 4-12 Calculation statements for the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition 26
Arithmetic Assignment Operators
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 27
Arithmetic Assignment Operators (contd)
Figure 4-13 How to use an arithmetic assignment operator
An Introduction to Programming with C++, Seventh Edition
28
Step 5Desk-Check the Program
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 locations 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 29
Step 5Desk-Check the Program (contd.)
Figure 4-14 Algorithms desk-check table from Chapter 2
Figure 4-15 Variable names and initial values entered in the programs desk-check table
An Introduction to Programming with C++, Seventh Edition 30
Step 5Desk-Check the Program (contd.)
Figure 4-16 Input values entered in the programs desk -check table
Figure 4-17 Desk-check table showing the result of the total bill without liquor charge calculation
An Introduction to Programming with C++, Seventh Edition
31
Step 5Desk-Check the Program (contd.)
Figure 4-18 Desk-check table showing the result of the tip calculation
Figure 4-19 Programs desk-check table showing the results of the second desk-check
An Introduction to Programming with C++, Seventh Edition 32
Step 6Evaluate and Modify the Program
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
33
Step 6Evaluate and Modify the Program (contd.)
Syntax errors result from breaking programming languages rules; cause compiler errors Logic errors dont 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 34
Step 6Evaluate and Modify the Program (contd.)
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 35
Step 6Evaluate and Modify the Program (contd.)
Figure 4-20 Process by which source code is translated into executable code
An Introduction to Programming with C++, Seventh Edition 36
Step 6Evaluate and Modify the Program (contd.)
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 37
Step 6Evaluate and Modify the Program (contd.)
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
38
Step 6Evaluate and Modify the Program (contd.)
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 39
Step 6Evaluate and Modify the Program (contd.)
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 functions code You enclose a functions code in a set of braces ({}) The code between the braces is called the function body
An Introduction to Programming with C++, Seventh Edition
40
Step 6Evaluate and Modify the Program (contd.)
Figure 4-21 Treyson Mobley program
An Introduction to Programming with C++, Seventh Edition 41
Step 6Evaluate and Modify the Program (contd.)
Figure 4-21 Treyson Mobley program (contd.)
An Introduction to Programming with C++, Seventh Edition 42
Step 6Evaluate and Modify the Program (contd.)
Figure 4-22 Command Prompt window
An Introduction to Programming with C++, Seventh Edition
43
Summary
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 44
Summary (contd.)
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
45
Summary (contd.)
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 deskcheck the program using the same data used to deskcheck the algorithm The sixth step is to evaluate and modify (if necessary) the program
An Introduction to Programming with C++, Seventh Edition 46
Summary (contd.)
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 47
Summary (contd.)
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 computers internal memory
An Introduction to Programming with C++, Seventh Edition 48
Summary (contd.)
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 49
Lab 4-1: Stop and Analyze
Figure 4-23 Examples for Lab 4-1
An Introduction to Programming with C++, Seventh Edition 50
Lab 4-2: Plan and Create
Plan and create an algorithm that displays the total amount a student owes for a semester
Figure 4-24 Problem specification for Lab 4-2
An Introduction to Programming with C++, Seventh Edition
51
Lab 4-3: Modify
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
52
Lab 4-4: Desk-Check
Desk-check the three lines of code shown in Figure 4-31
Figure 4-31 Code for Lab 4-4
An Introduction to Programming with C++, Seventh Edition
53
Lab 4-5: Debug
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
54
Introduction to Programming in C++ Seventh Edition
Chapter 5: The Selection Structure
Objectives
Include the selection structure in pseudocode and in a flowchart Code a selection structure using the if statement Include comparison operators in a selection structures condition Include logical operators in a selection structures condition Format numeric output
An Introduction to Programming with C++, Seventh Edition
Making Decisions
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 structures condition must be phrased as a Boolean expression (evaluates to true or false)
An Introduction to Programming with C++, Seventh Edition
Making Decisions (contd.)
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
An Introduction to Programming with C++, Seventh Edition 4
Making Decisions (contd.)
Figure 5-1 A problem that requires the sequence structure only
An Introduction to Programming with C++, Seventh Edition 5
Making Decisions (contd.)
Figure 5-2 A problem that requires the sequence structure and a single-alternative selection structure
An Introduction to Programming with C++, Seventh Edition 6
Making Decisions (contd.)
Figure 5-3 A problem that requires the sequence structure and a dual-alternative selection structure
An Introduction to Programming with C++, Seventh Edition 7
Flowcharting a 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
An Introduction to Programming with C++, Seventh Edition 8
Flowcharting a Selection Structure (contd)
Figure 5-4 Flowchart showing a singlealternative selection structure
An Introduction to Programming with C++, Seventh Edition 9
Flowcharting a Selection Structure (contd)
Figure 5-5 Flowchart showing a dual-alternative selection structure
An Introduction to Programming with C++, Seventh Edition 10
Coding a Selection Structure in C++
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
An Introduction to Programming with C++, Seventh Edition 11
Coding a Selection Structure in C++ (contd.)
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
An Introduction to Programming with C++, Seventh Edition 12
Coding a Selection Structure in C++ (contd.)
Figure 5-6 How to use the if statement
An Introduction to Programming with C++, Seventh Edition 13
Coding a Selection Structure in C++ (contd.)
Figure 5-6 How to use the if statement (contd)
An Introduction to Programming with C++, Seventh Edition 14
Comparison Operators
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
An Introduction to Programming with C++, Seventh Edition
15
Comparison Operators (contd.)
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
An Introduction to Programming with C++, Seventh Edition
16
Comparison Operators (contd.)
Expressions with comparison operators always evaluate to Boolean values Dont confuse equality operator (==) with assignment operator (=) Dont 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
An Introduction to Programming with C++, Seventh Edition
17
Comparison Operators (contd.)
Figure 5-7 How to use comparison operators in an if statements condition
An Introduction to Programming with C++, Seventh Edition 18
Comparison Operators (contd.)
Figure 5-8 Evaluation steps for an expression containing arithmetic and comparison operators
An Introduction to Programming with C++, Seventh Edition
19
Swapping Numeric Values
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
An Introduction to Programming with C++, Seventh Edition
20
Swapping Numeric Values (contd.)
Figure 5-9 IPO chart information and C++ instructions for the swapping program
An Introduction to Programming with C++, Seventh Edition 21
Swapping Numeric Values (contd.)
Figure 5-10 Illustration of the swapping concept
An Introduction to Programming with C++, Seventh Edition
22
Swapping Numeric Values (contd.)
Figure 5-11 Flowchart for the swapping program
An Introduction to Programming with C++, Seventh Edition
23
Swapping Numeric Values (contd.)
Figure 5-12 Sample run of the swapping program
An Introduction to Programming with C++, Seventh Edition
24
Displaying the Sum or Difference
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
An Introduction to Programming with C++, Seventh Edition
25
Displaying the Sum or Difference (contd.)
Figure 5-13 IPO chart information and C++ instructions for the sum or difference program
An Introduction to Programming with C++, Seventh Edition 26
Displaying the Sum or Difference (contd.)
Figure 5-14 Flowchart for sum or difference program
An Introduction to Programming with C++, Seventh Edition
27
Displaying the Sum or Difference (contd.)
Figure 5-15 Sample run of the sum or difference program
An Introduction to Programming with C++, Seventh Edition
28
Logical Operators
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
An Introduction to Programming with C++, Seventh Edition 29
Logical Operators (contd.)
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
An Introduction to Programming with C++, Seventh Edition 30
Logical Operators (contd.)
Figure 5-16 How to use logical operators in an if statements condition
An Introduction to Programming with C++, Seventh Edition
31
Logical Operators (contd.)
Figure 5-16 How to use logical operators in an if statements condition (contd)
An Introduction to Programming with C++, Seventh Edition 32
Logical Operators (contd.)
Figure 5-17 Truth tables for the logical operators
An Introduction to Programming with C++, Seventh Edition 33
Using the Truth Tables
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
An Introduction to Programming with C++, Seventh Edition
34
Calculating Gross Pay
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
An Introduction to Programming with C++, Seventh Edition
35
Calculating Gross Pay (contd.)
Figure 5-18 Examples of C++ instructions for the gross pay program
An Introduction to Programming with C++, Seventh Edition 36
Calculating Gross Pay (contd.)
Figure 5-19 First sample run of the gross pay programs code
Figure 5-20 Second sample run of the gross pay programs code
An Introduction to Programming with C++, Seventh Edition
37
Pass/Fail Program
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
An Introduction to Programming with C++, Seventh Edition 38
Pass/Fail Program (contd)
Figure 5-21 Examples of C++ instructions for the Pass/Fail program
An Introduction to Programming with C++, Seventh Edition 39
Pass/Fail Program (contd.)
Figure 5-22 First sample run of the Pass/Fail programs code
Figure 5-23 Second sample run of the Pass/Fail programs code
An Introduction to Programming with C++, Seventh Edition 40
Summary of Operators
Figure 5-24 Listing and an example of arithmetic, comparison, and logical operators
An Introduction to Programming with C++, Seventh Edition 41
Converting a Character to Uppercase or Lowercase
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 functions syntax is called an argument information the function needs to perform its task
An Introduction to Programming with C++, Seventh Edition 42
Converting a Character to Uppercase or Lowercase (contd.)
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
An Introduction to Programming with C++, Seventh Edition
43
Converting a Character to Uppercase or Lowercase (contd.)
Figure 5-25 How to use the toupper and tolower functions
An Introduction to Programming with C++, Seventh Edition 44
Formatting Numeric Output
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
An Introduction to Programming with C++, Seventh Edition 45
Formatting Numeric Output (contd.)
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
An Introduction to Programming with C++, Seventh Edition 46
Formatting Numeric Output (contd.)
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 arent 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
An Introduction to Programming with C++, Seventh Edition 47
Formatting Numeric Output (contd.)
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
An Introduction to Programming with C++, Seventh Edition 48
Formatting Numeric Output (contd.)
Figure 5-26 How to use the fixed and scientific stream manipulators
An Introduction to Programming with C++, Seventh Edition 49
Formatting Numeric Output (contd.)
Figure 5-27 How to use the setprecision stream manipulator
An Introduction to Programming with C++, Seventh Edition 50
Summary
Selection structure used when you want a program to make a decision before choosing next instruction Selection structures 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
An Introduction to Programming with C++, Seventh Edition 51
Summary (contd.)
A diamond (decision symbol) is used to represent a selection structures 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 {})
An Introduction to Programming with C++, Seventh Edition
52
Summary (contd.)
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 Dont use == and != to compare real numbers Local variables can only be used in the statement block in which they are declared
An Introduction to Programming with C++, Seventh Edition
53
Summary (contd.)
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
An Introduction to Programming with C++, Seventh Edition 54
Summary (contd.)
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
An Introduction to Programming with C++, Seventh Edition
55
Lab 5-1: Stop and Analyze
Figure 5-28 Program for Lab 5-1
An Introduction to Programming with C++, Seventh Edition 56
Lab 5-2: Plan and Create
Plan and create an algorithm for the manager of the Willow Springs Health Club
Figure 5-29 Problem specification for Lab 5-2
An Introduction to Programming with C++, Seventh Edition 57
Lab 5-3: Modify
Currently, the if statements 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
An Introduction to Programming with C++, Seventh Edition
58
Lab 5-4: Desk-Check
Desk-check the code shown in Figure 5-34 using the letter P Why is it inefficient? How could you improve it?
Figure 5-35 Code for Lab 5-4
An Introduction to Programming with C++, Seventh Edition 59
Lab 5-5: Debug
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
An Introduction to Programming with C++, Seventh Edition
60
Introduction to Programming in C++ Seventh Edition
Chapter 6: More on the Selection Structure
Objectives
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++
An Introduction to Programming with C++, Seventh Edition
Making Decisions
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
An Introduction to Programming with C++, Seventh Edition 3
Making Decisions (contd.)
Figure 6-1 Problem that requires a selection structure
An Introduction to Programming with C++, Seventh Edition 4
Making Decisions (contd.)
Figure 6-2 Problem that requires a nested selection structure
An Introduction to Programming with C++, Seventh Edition 5
Making Decisions (contd.)
Figure 6-3 Problem that requires two nested selection structures
An Introduction to Programming with C++, Seventh Edition 6
Flowcharting a Nested Selection Structure
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
An Introduction to Programming with C++, Seventh Edition
Flowcharting a Nested Selection Structure (contd.)
Figure 6-6 Problem specification for voter eligibility problem
An Introduction to Programming with C++, Seventh Edition
Flowcharting a Nested Selection Structure (contd.)
Figure 6-6 A correct solution to the voter eligibility problem
An Introduction to Programming with C++, Seventh Edition 9
Flowcharting a Nested Selection Structure (contd.)
Figure 6-7 Another correct solution to the voter eligibility problem
An Introduction to Programming with C++, Seventh Edition 10
Coding a Nested Selection Structure
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
An Introduction to Programming with C++, Seventh Edition
11
Coding a Nested Selection Structure (contd.)
Figure 6-8 Modified problem specification for the health club problem from Chapter 5s Lab 5-2
An Introduction to Programming with C++, Seventh Edition 12
Coding a Nested Selection Structure (contd.)
Figure 6-8 Modified problem specification for the health club problem from Chapter 5s Lab 5-2 (contd)
An Introduction to Programming with C++, Seventh Edition
13
Coding a Nested Selection Structure (contd.)
Figure 6-9 Sample run of the modified health club program
An Introduction to Programming with C++, Seventh Edition
14
Coding a Nested Selection Structure (contd.)
Figure 6-10 Flowchart for the modified health club program
An Introduction to Programming with C++, Seventh Edition 15
Logic Errors in Selection Structures
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
An Introduction to Programming with C++, Seventh Edition
16
Logic Errors in Selection Structures (contd.)
Figure 6-11 A correct algorithm for the bonus problem
An Introduction to Programming with C++, Seventh Edition
17
Logic Errors in Selection Structures (contd.)
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
An Introduction to Programming with C++, Seventh Edition 18
Logic Errors in Selection Structures (contd.)
Figure 6-15 Desk-check table after completing the second desk-check
Figure 6-16 Desk-check table after completing the third desk-check
An Introduction to Programming with C++, Seventh Edition 19
First Logic Error
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
An Introduction to Programming with C++, Seventh Edition
20
First Logic Error (contd.)
Figure 6-17 Correct algorithm and incorrect algorithm containing the first logic error
An Introduction to Programming with C++, Seventh Edition
21
First Logic Error (contd.)
Figure 6-18 Desk-check table for the incorrect algorithm in Figure 6-17
An Introduction to Programming with C++, Seventh Edition
22
Second Logic Error
Reversing outer and nested selection structures
Figure 6-19 Correct algorithm and an incorrect algorithm containing the second logic error
An Introduction to Programming with C++, Seventh Edition 23
Second Logic Error (contd.)
Figure 6-20 Desk-check table for the incorrect algorithm in Figure 6-19
An Introduction to Programming with C++, Seventh Edition
24
Third Logic Error
Using an unnecessary nested selection structure Often will produce the correct result, but will be inefficient
An Introduction to Programming with C++, Seventh Edition
25
Third Logic Error (contd.)
Figure 6-21 Correct algorithm and an incorrect algorithm containing the third logic error
An Introduction to Programming with C++, Seventh Edition 26
Third Logic Error (contd.)
Figure 6-22 Desk-check table for inefficient algorithm in Figure 6-21
An Introduction to Programming with C++, Seventh Edition
27
Multiple-Alternative Selection Structures
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
An Introduction to Programming with C++, Seventh Edition 28
Multiple-Alternative Selection Structures (contd.)
Figure 6-25 Problem specification for Kindlon High School problem
An Introduction to Programming with C++, Seventh Edition 29
Multiple-Alternative Selection Structures (contd.)
Figure 6-25 IPO chart for the Kindlon High School problem
An Introduction to Programming with C++, Seventh Edition
30
Multiple-Alternative Selection Structures (contd.)
Figure 6-26 Flowchart for the Kindlon High School problem
An Introduction to Programming with C++, Seventh Edition 31
Multiple-Alternative Selection Structures (contd.)
Figure 6-27 Two ways of coding the multiple-alternative selection structure from Figures 6-25 and 6-26
An Introduction to Programming with C++, Seventh Edition 32
The switch Statement
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
An Introduction to Programming with C++, Seventh Edition 33
The switch Statement (contd.)
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
An Introduction to Programming with C++, Seventh Edition
34
The switch Statement (contd.)
Each case clause contains one or more statements processed when selector expression matches that cases 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 statements closing brace
An Introduction to Programming with C++, Seventh Edition 35
The switch Statement (contd.)
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
An Introduction to Programming with C++, Seventh Edition 36
The switch Statement (contd.)
Figure 6-28 How to use the switch statement
An Introduction to Programming with C++, Seventh Edition 37
The switch Statement (contd.)
Example similar to code in Figure 6-28
An Introduction to Programming with C++, Seventh Edition 38
The switch Statement (contd.)
Figure 6-29 Problem specification for the Warren Company problem
An Introduction to Programming with C++, Seventh Edition
39
The switch Statement (contd.)
Figure 6-29 IPO chart and C++ instructions for the Warren Company problem
An Introduction to Programming with C++, Seventh Edition 40
The switch Statement (contd.)
Figure 6-30 Flowchart for the Warren Company problem
An Introduction to Programming with C++, Seventh Edition 41
Summary
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
An Introduction to Programming with C++, Seventh Edition
42
Summary (contd.)
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
An Introduction to Programming with C++, Seventh Edition
43
Summary (contd.)
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)
An Introduction to Programming with C++, Seventh Edition
44
Lab 6-1: Stop and Analyze
Figure 6-31 Flowchart for Lab 6-1
An Introduction to Programming with C++, Seventh Edition 45
Lab 6-2: Plan and Create
Figure 6-32 Problem specification and calculation examples for Lab 6-2
An Introduction to Programming with C++, Seventh Edition 46
Lab 6-3: Modify
Modify the program in Lab 6-2 to calculate commission based on information in Figure 6-38
Figure 6-38 Problem specification for Lab 6-3
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
An Introduction to Programming with C++, Seventh Edition 47
Lab 6-4: Desk-Check
Figure 6-39 Code for Lab 6-4
An Introduction to Programming with C++, Seventh Edition 48
Lab 6-5: Debug
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
An Introduction to Programming with C++, Seventh Edition
49
Introduction to Programming in C++ Seventh Edition
Chapter 7: The Repetition Structure
Objectives
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
An Introduction to Programming with C++, Seventh Edition
Repeating Program Instructions
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)
An Introduction to Programming with C++, Seventh Edition 3
Repeating Program Instructions (contd.)
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
An Introduction to Programming with C++, Seventh Edition
Repeating Program Instructions (contd.)
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
An Introduction to Programming with C++, Seventh Edition
Repeating Program Instructions (contd.)
Figure 7-1 A problem that requires the sequence and selection structures
An Introduction to Programming with C++, Seventh Edition
Repeating Program Instructions (contd.)
Figure 7-2 A problem that requires the sequence and repetition structures
An Introduction to Programming with C++, Seventh Edition 7
Using a Pretest Loop to Solve a RealWorld Problem
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 loops 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
An Introduction to Programming with C++, Seventh Edition
Using a Pretest Loop to Solve a RealWorld Problem (cont.)
After each processing of the loop body (iteration), the loops 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
An Introduction to Programming with C++, Seventh Edition
Using a Pretest Loop to Solve a RealWorld Problem (contd.)
Figure 7-4 Problem specification and IPO chart for the Totally Sweet Shoppe program
An Introduction to Programming with C++, Seventh Edition 10
Using a Pretest Loop to Solve a RealWorld Problem (contd.)
Figure 7-5 Problem specification and IPO chart for the Wheels & More program
An Introduction to Programming with C++, Seventh Edition 11
Using a Pretest Loop to Solve a RealWorld Problem (contd.)
Figure 7-6 Components of the Wheels & More algorithm
An Introduction to Programming with C++, Seventh Edition
12
Flowcharting a Pretest Loop
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
An Introduction to Programming with C++, Seventh Edition
13
Flowcharting a Pretest Loop (contd.)
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 loops 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
An Introduction to Programming with C++, Seventh Edition
14
Flowcharting a Pretest Loop (contd.)
Figure 7-7 Wheels & More algorithm shown in flowchart form
An Introduction to Programming with C++, Seventh Edition 15
Flowcharting a Pretest Loop (contd.)
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 employees information recorded in the desk -check table
An Introduction to Programming with C++, Seventh Edition 16
Flowcharting a Pretest Loop (contd.)
Figure 7-11 Second employees information recorded in the desk -check table
Figure 7-12 Completed desk-check table
An Introduction to Programming with C++, Seventh Edition
17
The while Statement
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
An Introduction to Programming with C++, Seventh Edition 18
The while Statement (contd.)
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
An Introduction to Programming with C++, Seventh Edition
19
The while Statement (contd.)
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
An Introduction to Programming with C++, Seventh Edition
20
The while Statement (contd.)
Figure 7-13 How to use the while statement
An Introduction to Programming with C++, Seventh Edition 21
The while Statement (contd.)
An alternate example using the while statement
An Introduction to Programming with C++, Seventh Edition 22
The while Statement (contd.)
Figure 7-14 IPO chart information and C++ instructions for the Wheels & More program
An Introduction to Programming with C++, Seventh Edition 23
The while Statement (contd.)
Figure 7-15 A sample run of the Wheels & More program
An Introduction to Programming with C++, Seventh Edition
24
Using Counters and Accumulators
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
An Introduction to Programming with C++, Seventh Edition
25
Using Counters and Accumulators (contd.)
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
An Introduction to Programming with C++, Seventh Edition 26
The Sales Express Program
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)
An Introduction to Programming with C++, Seventh Edition
27
The Sales Express Program (contd.)
Figure 7-17 Problem specification for the Sales Express program
An Introduction to Programming with C++, Seventh Edition
28
The Sales Express Program (contd.)
Figure 7-17 IPO chart information and C++ instructions for the Sales Express program
An Introduction to Programming with C++, Seventh Edition 29
The Sales Express Program (contd.)
Figure 7-17 IPO chart information and C++ instructions for the Sales Express program (contd)
An Introduction to Programming with C++, Seventh Edition 30
The Sales Express Program (contd.)
Figure 7-18 Flowchart for the Sales Express program
An Introduction to Programming with C++, Seventh Edition 31
The Sales Express Program (contd.)
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
An Introduction to Programming with C++, Seventh Edition
32
The Sales Express Program (contd.)
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
An Introduction to Programming with C++, Seventh Edition
33
The Sales Express Program (contd.)
Figure 7-23 First sample run of the Sales Express program
Figure 7-24 Second sample run of the Sales Express program
An Introduction to Programming with C++, Seventh Edition
34
Counter-Controlled Pretest Loops
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
An Introduction to Programming with C++, Seventh Edition
35
Counter-Controlled Pretest Loops (contd.)
Figure 7-25 Problem specification for the Jasper Music Company program
An Introduction to Programming with C++, Seventh Edition
36
Counter-Controlled Pretest Loops (contd.)
Figure 7-25 IPO chart information and C++ instructions for the Jasper Music Company program
An Introduction to Programming with C++, Seventh Edition 37
Counter-Controlled Pretest Loops (contd.)
Figure 7-26 Flowchart for the Jasper Music Company program
An Introduction to Programming with C++, Seventh Edition 38
Counter-Controlled Pretest Loops (contd.)
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
An Introduction to Programming with C++, Seventh Edition 39
Counter-Controlled Pretest Loops (contd.)
Figure 7-30 Results of processing loop body instructions third time
Figure 7-31 Sample run of Jasper Music Company program
An Introduction to Programming with C++, Seventh Edition 40
The for Statement
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
An Introduction to Programming with C++, Seventh Edition 41
The for Statement (contd.)
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
An Introduction to Programming with C++, Seventh Edition
42
The for Statement (contd.)
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
An Introduction to Programming with C++, Seventh Edition 43
The for Statement (contd.)
Figure 7-32 How to use the for statement
An Introduction to Programming with C++, Seventh Edition 44
The for Statement (contd.)
Figure 7-33 Processing steps for the code shown in Example 1 in Figure 7-32
An Introduction to Programming with C++, Seventh Edition
45
The Holmes Supply Program
Extended example of a problem and program solution (following slides)
Program totals up the sales from three stores using a for loop
Figure 7-34 Problem specification for the Holmes Supply Company program
An Introduction to Programming with C++, Seventh Edition 46
The Holmes Supply Program (contd.)
Figure 7-34 IPO chart information and C++ instructions for the Holmes Supply Company program
An Introduction to Programming with C++, Seventh Edition 47
The Holmes Supply Program (contd.)
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
An Introduction to Programming with C++, Seventh Edition 48
The Holmes Supply Program (contd.)
Figure 7-38 Desk-check table after update argument is processed third time
Figure 7-39 Sample run of Holmes Supply Company program
An Introduction to Programming with C++, Seventh Edition 49
The Colfax Sales 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
Figure 7-40 Problem specification for the Colfax Sales program
An Introduction to Programming with C++, Seventh Edition 50
The Colfax Sales Program (contd.)
Figure 7-40 IPO chart information and C++ instructions for the Colfax Sales program
An Introduction to Programming with C++, Seventh Edition 51
The Colfax Sales Program (contd.)
Figure 7-41 Processing steps for the code in Figure 7-40
An Introduction to Programming with C++, Seventh Edition 52
The Colfax Sales Program (contd.)
Figure 7-41 Processing steps for the code in Figure 7-40 (contd.)
An Introduction to Programming with C++, Seventh Edition
53
The Colfax Sales Program (contd.)
Figure 7-42 A sample run of the Colfax Sales program
An Introduction to Programming with C++, Seventh Edition
54
The Colfax Sales Program (contd.)
Figure 7-43 Colfax Sales algorithm shown in flowchart form
An Introduction to Programming with C++, Seventh Edition
55
Another Version of the Wheels & More Program
Alternative version of the Wheels & More program (following slides)
Uses a for loop instead of a while loop
An Introduction to Programming with C++, Seventh Edition
56
Another Version of the Wheels & More Program (contd.)
Figure 7-44 IPO chart information and modified C++ instructions for the Wheels & More program
An Introduction to Programming with C++, Seventh Edition 57
Another Version of the Wheels & More Program (contd.)
Figure 7-45 Processing steps for the code shown in Figure 7-44
An Introduction to Programming with C++, Seventh Edition 58
Summary
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
An Introduction to Programming with C++, Seventh Edition
59
Summary (contd.)
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
An Introduction to Programming with C++, Seventh Edition 60
Summary (contd.)
Input instruction that appears above a pretest loops 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 structures condition
An Introduction to Programming with C++, Seventh Edition
61
Summary (contd.)
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++
An Introduction to Programming with C++, Seventh Edition
62
Lab 7-1: Stop and Analyze
Study the program in Figure 7-46 and answer the questions The program calculates the average outside temperature
An Introduction to Programming with C++, Seventh Edition
63
Lab 7-2: Plan and Create
Figure 7-47 Problem specification for Lab 7-2
An Introduction to Programming with C++, Seventh Edition 64
Lab 7-3: Modify
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?
An Introduction to Programming with C++, Seventh Edition 65
Lab 7-4: Desk-Check
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
Figure 7-53 Code for Lab 7-4
An Introduction to Programming with C++, Seventh Edition 66
Lab 7-5: Debug
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
An Introduction to Programming with C++, Seventh Edition
67
Introduction to Programming in C++ Seventh Edition
Chapter 8: More on the Repetition Structure
Objectives
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
An Introduction to Programming with C++, Seventh Edition
Posttest Loops
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 loops instructions are always processed at least once Pretest loops instructions may never be processed
An Introduction to Programming with C++, Seventh Edition
Posttest Loops (contd.)
Figure 8-1 Problem specification, illustrations, and solutions containing pretest and posttest loops
An Introduction to Programming with C++, Seventh Edition 4
Posttest Loops (contd.)
Figure 8-2 Selection structure added to Solution 2 from Figure 8-1
An Introduction to Programming with C++, Seventh Edition
Flowcharting a Posttest Loop
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
An Introduction to Programming with C++, Seventh Edition
Flowcharting a Posttest Loop (contd.)
Figure 8-3 Wheels & More problem specification & algorithms (continues)
An Introduction to Programming with C++, Seventh Edition 7
Flowcharting a Posttest Loop (contd.)
Figure 8-3 Wheels & More problem specification & algorithms (continued)
An Introduction to Programming with C++, Seventh Edition 8
Flowcharting a Posttest Loop (contd.)
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
An Introduction to Programming with C++, Seventh Edition 9
The do while Statement
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
An Introduction to Programming with C++, Seventh Edition 10
The do while Statement (contd.)
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
An Introduction to Programming with C++, Seventh Edition
11
The do while Statement (contd.)
Figure 8-9 How to use the do while statement
An Introduction to Programming with C++, Seventh Edition 12
The do while Statement (contd.)
Figure 8-9 How to use the do while statement (contd.)
An Introduction to Programming with C++, Seventh Edition
13
The do while Statement (contd.)
Figure 8-10 IPO chart information and C++ instructions for the Wheels & More program
An Introduction to Programming with C++, Seventh Edition 14
The do while Statement (contd.)
Figure 8-11 A sample run of the Wheels & More program
An Introduction to Programming with C++, Seventh Edition
15
Nested Repetition Structures
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
An Introduction to Programming with C++, Seventh Edition
16
Nested Repetition Structures (contd.)
Figure 8-12 Logic used by a clocks minute and second hands
An Introduction to Programming with C++, Seventh Edition
17
Nested Repetition Structures (contd.)
Figure 8-13 Problem specification and solution that requires a loop
An Introduction to Programming with C++, Seventh Edition 18
Nested Repetition Structures (contd.)
Figure 8-14 Modified problem specification and solution that requires a nested loop
An Introduction to Programming with C++, Seventh Edition
19
The Asterisks Program
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
An Introduction to Programming with C++, Seventh Edition
20
The Asterisks Program (contd.)
Figure 8-15 Problem specification IPO chart information and C++ instructions for the asterisks program
An Introduction to Programming with C++, Seventh Edition 21
The Asterisks Program (contd.)
Figure 8-15 IPO chart information and C++ instructions for the asterisks program (contd.)
An Introduction to Programming with C++, Seventh Edition 22
The Asterisks Program (contd.)
Figure 8-16 Completed desk-check table for the asterisks program
Figure 8-17 Sample run of the asterisks program
An Introduction to Programming with C++, Seventh Edition 23
The Asterisks Program (contd.)
Figure 8-18 Problem specification, IPO chart information, and C++ instructions for the modified asterisks program
An Introduction to Programming with C++, Seventh Edition
24
The Asterisks Program (contd.)
Figure 8-18 Problem specification, IPO chart information, and C++ instructions for the modified asterisks program (cont.)
An Introduction to Programming with C++, Seventh Edition 25
The Asterisks Program (contd.)
Figure 8-19 Desk-check table and output after the nested loops cout statement is processed the first time
Figure 8-20 Desk-check table and output after the nested loops cout statement is processed the second time
An Introduction to Programming with C++, Seventh Edition 26
The Asterisks Program (contd.)
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
An Introduction to Programming with C++, Seventh Edition 27
The Asterisks Program (contd.)
Figure 8-23 Desk-check table and output after the nested loop ends the third time
An Introduction to Programming with C++, Seventh Edition
28
The Asterisks Program (contd.)
Figure 8-24 Sample run of the modified asterisks program
An Introduction to Programming with C++, Seventh Edition
29
The Savings Calculator 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
An Introduction to Programming with C++, Seventh Edition
30
The Savings Calculator Program (contd.)
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 31
The Savings Calculator Program (contd.)
Figure 8-26 Flowchart for the savings calculator program
An Introduction to Programming with C++, Seventh Edition 32
The pow Function
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
An Introduction to Programming with C++, Seventh Edition
33
The pow Function (contd.)
Figure 8-27 How to use the pow function
An Introduction to Programming with C++, Seventh Edition 34
Coding the Savings Calculator Program
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%
An Introduction to Programming with C++, Seventh Edition
35
Coding the Savings Calculator Program (contd.)
Figure 8-28 IPO chart information and C++ instructions for the savings calculator program
An Introduction to Programming with C++, Seventh Edition
36
Coding the Savings Calculator Program (contd.)
Figure 8-28 IPO chart information and C++ instructions for the savings calculator program
An Introduction to Programming with C++, Seventh Edition
37
Coding the Savings Calculator Program (contd.)
Figure 8-29 Savings calculator program
An Introduction to Programming with C++, Seventh Edition 38
Coding the Savings Calculator Program (contd.)
Figure 8-30 Sample run of savings calculator program
An Introduction to Programming with C++, Seventh Edition
39
Modifying the Savings Calculator Program
Savings calculator program is modified to calculate the total account value for interest rates of 2%, 3%, and 4%
An Introduction to Programming with C++, Seventh Edition
40
Modifying the Savings Calculator Program (contd.)
Figure 8-31 IPO chart information and C++ instructions for the modified savings calculator program
An Introduction to Programming with C++, Seventh Edition 41
Modifying the Savings Calculator Program (contd.)
Figure 8-31 Modified IPO chart information and C++ instructions (contd.)
An Introduction to Programming with C++, Seventh Edition 42
Modifying the Savings Calculator Program (contd.)
Figure 8-32 Flowchart for the modified savings calculator program
An Introduction to Programming with C++, Seventh Edition 43
Modifying the Savings Calculator Program (contd.)
Figure 8-33 Modified savings calculator program
An Introduction to Programming with C++, Seventh Edition 44
Modifying the Savings Calculator Program (contd.)
Figure 8-34 Sample run of modified savings calculator program
An Introduction to Programming with C++, Seventh Edition 45
Summary
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++
An Introduction to Programming with C++, Seventh Edition 46
Summary (contd.)
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
An Introduction to Programming with C++, Seventh Edition
47
Lab 8-1: Stop and Analyze
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
An Introduction to Programming with C++, Seventh Edition
48
Lab 8-2: Plan and Create
Figure 8-37 Problem specification for Lab 8-2
An Introduction to Programming with C++, Seventh Edition 49
Lab 8-3: Modify
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
An Introduction to Programming with C++, Seventh Edition
50
Lab 8-4: Desk-Check
Desk-check the code in Figure 8-43 What will the code display on the computer screen?
Figure 8-43 Code for Lab 8-4
An Introduction to Programming with C++, Seventh Edition 51
Lab 8-5: Debug
Follow the instructions for starting C++ and opening the Lab8-5.cpp file Debug the program
An Introduction to Programming with C++, Seventh Edition
52
Introduction to Programming in C++ Seventh Edition
Chapter 9: Value-Returning Functions
Objectives
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 variables scope and lifetime
An Introduction to Programming with C++, Seventh Edition
Functions
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
An Introduction to Programming with C++, Seventh Edition
Functions (contd.)
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
An Introduction to Programming with C++, Seventh Edition
Functions (contd.)
Figure 9-1 Illustrations of value-returning and void functions
An Introduction to Programming with C++, Seventh Edition 5
Value-Returning Functions
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
An Introduction to Programming with C++, Seventh Edition 6
The Hypotenuse Program
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
An Introduction to Programming with C++, Seventh Edition
The Hypotenuse Program (contd.)
Figure 9-2 Problem specification, calculation example, and IPO chart for the hypotenuse program
An Introduction to Programming with C++, Seventh Edition 8
The Hypotenuse Program (contd.)
Figure 9-3 Flowchart of the hypotenuse program
An Introduction to Programming with C++, Seventh Edition 9
Finding the Square Root of a Number
sqrt function is a built-in value-returning function that returns a numbers 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
An Introduction to Programming with C++, Seventh Edition
10
Finding the Square Root of a Number (contd.)
Figure 9-4 How to use the sqrt function
An Introduction to Programming with C++, Seventh Edition 11
Finding the Square Root of a Number (contd.)
Figure 9-5 IPO chart information and C++ instructions for the hypotenuse program
An Introduction to Programming with C++, Seventh Edition 12
Finding the Square Root of a Number (contd.)
Figure 9-6 Hypotenuse program
An Introduction to Programming with C++, Seventh Edition 13
Finding the Square Root of a Number (contd.)
Figure 9-7 Sample run of hypotenuse program
An Introduction to Programming with C++, Seventh Edition
14
The Random Addition Problems 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
An Introduction to Programming with C++, Seventh Edition
15
The Random Addition Problems Program (contd.)
Figure 9-8 Problem specification for random addition problems program
An Introduction to Programming with C++, Seventh Edition
16
The Random Addition Problems Program (contd.)
Figure 9-8 IPO chart for random addition problems program
An Introduction to Programming with C++, Seventh Edition 17
The Random Addition Problems Program (contd.)
Figure 9-9 Flowchart for random addition problems program
An Introduction to Programming with C++, Seventh Edition 18
Generating Random Integers
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)
An Introduction to Programming with C++, Seventh Edition
19
Generating Random Integers (contd.)
rand functions syntax: rand()
Doesnt 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
An Introduction to Programming with C++, Seventh Edition
20
Generating Random Integers (contd.)
Figure 9-10 How to use the rand function
An Introduction to Programming with C++, Seventh Edition 21
Generating Random Integers (contd.)
Figure 9-11 How to generate random integers within a specific range
An Introduction to Programming with C++, Seventh Edition 22
Generating Random Integers (contd.)
Figure 9-11 How to generate random integers within a specific range (contd.)
An Introduction to Programming with C++, Seventh Edition 23
Generating Random Integers (contd.)
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
An Introduction to Programming with C++, Seventh Edition
24
Generating Random Integers (contd.)
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
An Introduction to Programming with C++, Seventh Edition
25
Generating Random Integers (contd.)
Figure 9-12 How to use the srand function
An Introduction to Programming with C++, Seventh Edition 26
Generating Random Integers (contd.)
Figure 9-13 IPO chart information and C++ instructions for the random addition problems program
An Introduction to Programming with C++, Seventh Edition
27
Generating Random Integers (contd.)
Figure 9-13 IPO chart information and C++ instructions for the random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition 28
Generating Random Integers (contd.)
Figure 9-14 Random addition problems program
An Introduction to Programming with C++, Seventh Edition 29
Generating Random Integers (contd.)
Figure 9-14 Random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition
30
Generating Random Integers (contd.)
Figure 9-15 Sample run of random addition problems program
An Introduction to Programming with C++, Seventh Edition
31
Creating Program-Defined ValueReturning Functions
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 functions purpose Memory locations in parameterList are called formal parameters
Each stores an item of information passed to the function when it is called
An Introduction to Programming with C++, Seventh Edition 32
Creating Program-Defined ValueReturning Functions (contd.)
Function body contains instructions for performing the functions 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
An Introduction to Programming with C++, Seventh Edition 33
Creating Program-Defined ValueReturning Functions (contd.)
Figure 9-16 IPO charts for modified random addition problems program
An Introduction to Programming with C++, Seventh Edition
34
Creating Program-Defined ValueReturning Functions (contd.)
Figure 9-16 IPO charts for modified random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition 35
Creating Program-Defined ValueReturning Functions (contd.)
Figure 9-17 How to create a program-defined value-returning function
An Introduction to Programming with C++, Seventh Edition
36
Creating Program-Defined ValueReturning Functions (contd.)
Figure 9-17 How to create a program-defined value-returning function (contd.)
An Introduction to Programming with C++, Seventh Edition
37
Calling a Function
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
An Introduction to Programming with C++, Seventh Edition
38
Calling a Function (contd.)
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
An Introduction to Programming with C++, Seventh Edition
39
Calling a Function (contd.)
C++ allows you to pass either a variables value or its address to a function Passing a variables value is referred to as passing by value Passing a variables 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)
An Introduction to Programming with C++, Seventh Edition
40
Calling a Function (contd.)
Figure 9-18 How to call a function
An Introduction to Programming with C++, Seventh Edition 41
Calling a Function (contd.)
Figure 9-18 How to call a function (contd.)
An Introduction to Programming with C++, Seventh Edition 42
Calling a Function (contd.)
Figure 9-19 Function calls and function definitions
An Introduction to Programming with C++, Seventh Edition 43
Calling a Function (contd.)
Figure 9-20 IPO chart information and C++ instructions for the modified random addition problems program
An Introduction to Programming with C++, Seventh Edition
44
Calling a Function (contd.)
Figure 9-20 IPO chart information and C++ instructions for the modified random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition
45
Calling a Function (contd.)
Figure 9-20 IPO chart information and C++ instructions for the modified random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition 46
Calling a Function (contd.)
Figure 9-20 IPO chart information and C++ instructions for the modified random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition 47
Function Prototypes
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 functions 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
An Introduction to Programming with C++, Seventh Edition
48
Function Prototypes (contd.)
Figure 9-21 How to write a function prototype
An Introduction to Programming with C++, Seventh Edition 49
Function Prototypes (contd.)
Figure 9-22 Modified random addition problems program
An Introduction to Programming with C++, Seventh Edition 50
Function Prototypes (contd.)
Figure 9-22 Modified random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition
51
The Western Elementary School Program
Modification of the random addition problems program User should have the option to specify the range of random numbers that the program generates Programs tasks are divided up into functions
An Introduction to Programming with C++, Seventh Edition
52
The Western Elementary School Program (contd.)
Figure 9-23 Western Elementary School program
An Introduction to Programming with C++, Seventh Edition 53
The Western Elementary School Program (contd.)
Figure 9-23 Western Elementary School program (contd.)
An Introduction to Programming with C++, Seventh Edition 54
The Western Elementary School Program (contd.)
Figure 9-24 Sample run of Western Elementary School program
An Introduction to Programming with C++, Seventh Edition 55
The Area Calculator Program
Program that uses a program-defined, value-returning function to calculate the area of a rectangle Input is rectangles length and width measurements Program calculates area and then displays it on the screen
An Introduction to Programming with C++, Seventh Edition
56
The Area Calculator Program (contd.)
Figure 9-25 Problem specification and IPO charts for area calculator program
An Introduction to Programming with C++, Seventh Edition
57
The Area Calculator Program (contd.)
Figure 9-25 Problem specification and IPO charts for the area calculator program (contd.)
An Introduction to Programming with C++, Seventh Edition 58
The Area Calculator Program (contd.)
Figure 9-26 Sample run of the area calculator program
An Introduction to Programming with C++, Seventh Edition
59
The Area Calculator Program (contd.)
Figure 9-27 Area calculator program
An Introduction to Programming with C++, Seventh Edition 60
The Area Calculator Program (contd.)
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
An Introduction to Programming with C++, Seventh Edition
61
The Area Calculator Program (contd.)
Figure 9-30 Desk-check table after getRectangleArea function ends
An Introduction to Programming with C++, Seventh Edition
62
The Scope and Lifetime of a Variable
A variables scope indicates where in the program the variable can be used A variables lifetime indicates how long the variable remains in the computers 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 functions parameterList have a local scope and are referred to as local variables
An Introduction to Programming with C++, Seventh Edition
63
The Scope and Lifetime of a Variable (contd.)
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
An Introduction to Programming with C++, Seventh Edition
64
The Scope and Lifetime of a Variable (contd.)
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 variables 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
An Introduction to Programming with C++, Seventh Edition
65
The Bonus Calculator Program
Program that calculates a salespersons 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)
An Introduction to Programming with C++, Seventh Edition
66
The Bonus Calculator Program (contd.)
Figure 9-31 Problem specification, IPO chart information, and C++ code for the main function
An Introduction to Programming with C++, Seventh Edition 67
The Bonus Calculator Program (contd.)
Figure 9-32 IPO chart information and C++ code for the getSales function
An Introduction to Programming with C++, Seventh Edition
68
The Bonus Calculator Program (contd.)
Figure 9-33 IPO chart information and C++ code for the getBonus function
An Introduction to Programming with C++, Seventh Edition
69
The Bonus Calculator Program (contd.)
Figure 9-35 Bonus calculator program
An Introduction to Programming with C++, Seventh Edition
70
The Bonus Calculator Program (contd.)
Figure 9-35 Bonus calculator program (contd.)
An Introduction to Programming with C++, Seventh Edition
71
The Bonus Calculator Program (contd.)
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
An Introduction to Programming with C++, Seventh Edition 72
The Bonus Calculator Program (contd.)
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
An Introduction to Programming with C++, Seventh Edition 73
The Bonus Calculator Program (contd.)
Figure 9-39 Desk-check table after getSales function ends
Figure 9-40 Desk-check table after getBonus function header is processed
An Introduction to Programming with C++, Seventh Edition 74
The Bonus Calculator Program (contd.)
Figure 9-41 Desk-check table after bonus is calculated
Figure 9-42 Desk-check table after getBonus function ends
An Introduction to Programming with C++, Seventh Edition 75
Summary
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
An Introduction to Programming with C++, Seventh Edition 76
Summary (contd.)
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)
An Introduction to Programming with C++, Seventh Edition
77
Summary (contd.)
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 functions assigned task
Surrounded by braces ({})
return statement returns the result of an expression to the calling function
An Introduction to Programming with C++, Seventh Edition 78
Summary (contd.)
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
An Introduction to Programming with C++, Seventh Edition
79
Summary (contd.)
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
An Introduction to Programming with C++, Seventh Edition
80
Lab 9-1: Stop and Analyze
Study the program in Figure 9-43, and then answer the questions
An Introduction to Programming with C++, Seventh Edition
81
Lab 9-2: Plan and Create
Figure 9-44 Problem specification for Lab 9-2
An Introduction to Programming with C++, Seventh Edition 82
Lab 9-3: Modify
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
An Introduction to Programming with C++, Seventh Edition
83
Lab 9-4: Desk-Check
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?
An Introduction to Programming with C++, Seventh Edition 84
Lab 9-5: Debug
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
An Introduction to Programming with C++, Seventh Edition
85
Introduction to Programming in C++ Seventh Edition
Chapter 10: Void Functions
Objectives
Create a void function Invoke a void function Pass information by reference to a function
An Introduction to Programming with C++, Seventh Edition
Functions
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
Doesnt need to return a value
An Introduction to Programming with C++, Seventh Edition
Functions (contd.)
Figure 10-1 Illustration of value-returning and void functions
An Introduction to Programming with C++, Seventh Edition 4
Creating Program-Defined Void Functions
Figure 10-2 How to create a program-defined void function
An Introduction to Programming with C++, Seventh Edition 5
Creating Program-Defined Void Functions (contd.)
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
An Introduction to Programming with C++, Seventh Edition
Creating Program-Defined Void Functions (contd.)
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program
An Introduction to Programming with C++, Seventh Edition
Creating Program-Defined Void Functions (contd.)
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 8
Creating Program-Defined Void Functions (contd.)
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 9
Creating Program-Defined Void Functions (contd.)
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 10
Creating Program-Defined Void Functions (contd.)
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 11
Creating Program-Defined Void Functions (contd.)
Figure 10-5 ABC Company program
An Introduction to Programming with C++, Seventh Edition 12
Creating Program-Defined Void Functions (contd.)
Figure 10-5 ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 13
Creating Program-Defined Void Functions (contd.)
Figure 10-6 Sample run of the ABC Company program
An Introduction to Programming with C++, Seventh Edition
14
Passing Variables to a Function
Recall you can pass a variables value or its address Passing a variables value is referred to as passing by value, while passing a variables 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
An Introduction to Programming with C++, Seventh Edition
15
Reviewing Passing Variables by Value
Passing a variable by value means that only a copy of the variables 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
An Introduction to Programming with C++, Seventh Edition
16
Reviewing Passing Variables by Value (contd.)
Figure 10-8 Age message program
An Introduction to Programming with C++, Seventh Edition 17
Reviewing Passing Variables by Value (contd.)
Figure 10-9 Desk-check table after the first three statements in the main function are processed
Figure 10-10 Desk-check table after the displayAge function header is processed
An Introduction to Programming with C++, Seventh Edition 18
Reviewing Passing Variables by Value (contd.)
Figure 10-11 Desk-check table after the displayAge function ends
Figure 10-12 Sample run of the age message program
An Introduction to Programming with C++, Seventh Edition 19
Passing Variables by Reference
Passing a variables 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 functions header Ampersand (&) is the address-of operator
Tells the computer to pass the variables address rather than a copy of its contents
An Introduction to Programming with C++, Seventh Edition 20
Passing Variables by Reference (contd.)
If receiving function appears below main, you must also include the & in the receiving functions prototype You enter the & immediately before the name of the formal parameter in the prototype
If the prototype does not contain the formal parameters name, you enter a space followed by & after the formal parameters data type
Void functions use variables passed by reference to send information back to the calling function, instead of a return value
An Introduction to Programming with C++, Seventh Edition 21
Passing Variables by Reference (contd.)
Figure 10-13 Modified age message program
An Introduction to Programming with C++, Seventh Edition 22
Passing Variables by Reference (contd.)
Figure 10-14 Desk-check table after the declaration statement in the main function is processed
Figure 10-15 Desk-check table after the getAge function header is processed
An Introduction to Programming with C++, Seventh Edition 23
Passing Variables by Reference (contd.)
Figure 10-16 Desk-check table after the statements in the getAge function are processed
Figure 10-17 Desk-check table after the getAge function ends
An Introduction to Programming with C++, Seventh Edition 24
Passing Variables by Reference (contd.)
Figure 10-18 Desk-check table after the computer processes the displayAge function header
Figure 10-19 Desk-check table after the displayAge function ends
An Introduction to Programming with C++, Seventh Edition 25
Passing Variables by Reference (contd.)
Figure 10-20 Sample run of the modified age message program
An Introduction to Programming with C++, Seventh Edition
26
The Salary Program
Program that allows the user to enter an employees current salary and raise rate Computes the employees raise and new salary Program makes use of a void function that is passed two variables by value and two by reference
An Introduction to Programming with C++, Seventh Edition
27
The Salary Program (contd.)
Figure 10-22 IPO chart information and C++ instructions for the salary program
An Introduction to Programming with C++, Seventh Edition 28
The Salary Program (contd.)
Figure 10-22 IPO chart information and C++ instructions for the salary program (contd.)
An Introduction to Programming with C++, Seventh Edition
29
The Salary Program (contd.)
Figure 10-23 Salary program
An Introduction to Programming with C++, Seventh Edition 30
The Salary Program (contd.)
Figure 10-23 Salary program (contd.)
An Introduction to Programming with C++, Seventh Edition
31
The Salary Program (contd.)
Figure 10-24 Desk-check table after the statements on lines 15 through 24 are processed
Figure 10-25 Desk-check table after the computer processes the getNewPayInfo function header
An Introduction to Programming with C++, Seventh Edition 32
The Salary Program (contd.)
Figure 10-26 Desk-check table after the computer processes the statements in the getNewPayInfo function body
Figure 10-27 Desk-check table after the getNewPayInfo function ends
An Introduction to Programming with C++, Seventh Edition 33
The Salary Program (contd.)
Figure 10-28 Sample run of the salary program
An Introduction to Programming with C++, Seventh Edition
34
Summary
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
An Introduction to Programming with C++, Seventh Edition
35
Summary (contd.)
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 variables value is passed
Receiving function is not given access to the variable, so it cannot change the variables contents Computer uses data type and name of formal parameter to store a copy of the value
An Introduction to Programming with C++, Seventh Edition 36
Summary (contd.)
When a variable is passed by reference, the variables address in memory is passed
Receiving function can change variables 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 functions prototype
An Introduction to Programming with C++, Seventh Edition 37
Lab 10-1: Stop and Analyze
Study the code in Figure 10-30 and then answer the questions (sample run below)
Figure 10-29 Sample run of program for Lab 10-1
An Introduction to Programming with C++, Seventh Edition 38
Lab 10-2: Plan and Create
Figure 10-31 Problem specification and a sample calculation for Lab 10-2
An Introduction to Programming with C++, Seventh Edition
39
Lab 10-3: Modify
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
An Introduction to Programming with C++, Seventh Edition
40
Lab 10-4: Desk-Check
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
An Introduction to Programming with C++, Seventh Edition
41
Lab 10-5: Debug
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
An Introduction to Programming with C++, Seventh Edition
42
Introduction to Programming in C++ Seventh Edition
Chapter 11: One-Dimensional Arrays
Objectives
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 onedimensional array
An Introduction to Programming with C++, Seventh Edition
Objectives (contd.)
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
An Introduction to Programming with C++, Seventh Edition
Arrays
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
An Introduction to Programming with C++, Seventh Edition
Arrays (contd.)
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
An Introduction to Programming with C++, Seventh Edition
One-Dimensional Arrays
Variables in an array are stored in consecutive locations in computers 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 variables position in the array and is assigned by the computer when the array is created
An Introduction to Programming with C++, Seventh Edition 6
One-Dimensional Arrays (contd.)
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 arrays 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
An Introduction to Programming with C++, Seventh Edition
One-Dimensional Arrays (contd.)
Figure 11-1 Illustration of naming conventions for one-dimensional beatles array
An Introduction to Programming with C++, Seventh Edition 8
One-Dimensional Arrays (contd.)
Figure 11-2 Illustration of naming conventions for one-dimensional sales array
An Introduction to Programming with C++, Seventh Edition 9
One-Dimensional Arrays (contd.)
Figure 11-3 Problem specification and IPO chart for the XYZ Companys sales program
An Introduction to Programming with C++, Seventh Edition 10
Declaring and Initializing a OneDimensional Array
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)
An Introduction to Programming with C++, Seventh Edition 11
Declaring and Initializing a OneDimensional Array (contd.)
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
An Introduction to Programming with C++, Seventh Edition
12
Declaring and Initializing a OneDimensional Array (contd.)
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
An Introduction to Programming with C++, Seventh Edition
13
Declaring and Initializing a OneDimensional Array (contd.)
Figure 11-4 How to declare and initialize a one-dimensional array
An Introduction to Programming with C++, Seventh Edition 14
Entering Data into a One-Dimensional Array
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
An Introduction to Programming with C++, Seventh Edition
15
Entering Data into a One-Dimensional Array (contd.)
Figure 11-5 How to use an assignment statement to assign data to a one-dimensional array
An Introduction to Programming with C++, Seventh Edition 16
Entering Data into a One-Dimensional Array (contd.)
Figure 11-5 How to use an assignment statement to assign data to a one-dimensional array (cont.)
An Introduction to Programming with C++, Seventh Edition 17
Entering Data into a One-Dimensional Array (contd.)
Figure 11-6 How to use the extraction operator to store data in a one-dimensional array
An Introduction to Programming with C++, Seventh Edition
18
Entering Data into a One-Dimensional Array (contd.)
Figure 11-6 How to use the extraction operator to store data in a one-dimensional array (cont.)
An Introduction to Programming with C++, Seventh Edition
19
Displaying the Contents of a OneDimensional Array
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
An Introduction to Programming with C++, Seventh Edition
20
Displaying the Contents of a OneDimensional Array (contd.)
Figure 11-7 How to display the contents of a one-dimensional array
An Introduction to Programming with C++, Seventh Edition
21
Displaying the Contents of a OneDimensional Array (contd.)
Figure 11-7 How to display the contents of a one-dimensional array (cont.)
An Introduction to Programming with C++, Seventh Edition
22
Coding the XYZ Companys Sales Program
Program uses an array to store the sales made in each of the XYZ Companys four regions Allows the user to enter the sales amounts and then displays the amounts on the computer screen
An Introduction to Programming with C++, Seventh Edition
23
Coding the XYZ Companys Sales Program (contd.)
Figure 11-8 IPO chart information and C++ instructions for the XYZ Companys sales program
An Introduction to Programming with C++, Seventh Edition 24
Coding the XYZ Companys Sales Program (contd.)
Figure 11-9 The XYZ Companys sales program
An Introduction to Programming with C++, Seventh Edition 25
Coding the XYZ Companys Sales Program (contd.)
Figure 11-10 Sample run of XYZ Companys sales program
An Introduction to Programming with C++, Seventh Edition
26
Coding the XYZ Companys Sales Program (contd.)
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
An Introduction to Programming with C++, Seventh Edition 27
Coding the XYZ Companys Sales Program (contd.)
Figure 11-13 Desk-check table after Region 1s sales entered in array
Figure 11-14 Desk-check table after Region 2s sales entered in array
Figure 11-15 Desk-check table after Region 3s sales entered in array
An Introduction to Programming with C++, Seventh Edition 28
Coding the XYZ Companys Sales Program (contd.)
Figure 11-16 Desk-check table after Region 4s sales entered in array
Figure 11-17 Desk-check table after for loop on lines 15-20 ends
An Introduction to Programming with C++, Seventh Edition 29
Coding the XYZ Companys Sales Program (contd.)
Figure 11-18 Desk-check table after the initialization argument on line 23 is processed
Figure 11-19 Desk-check table after the for loop on lines 23 through 27 ends
An Introduction to Programming with C++, Seventh Edition 30
Passing a One-Dimensional Array to a Function
You can pass an array to a function by including the arrays 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
An Introduction to Programming with C++, Seventh Edition
31
Passing a One-Dimensional Array to a Function (contd.)
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 parameters 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
An Introduction to Programming with C++, Seventh Edition 32
Passing a One-Dimensional Array to a Function (contd.)
Figure 11-20 XYZ Companys modified sales program
An Introduction to Programming with C++, Seventh Edition
33
Passing a One-Dimensional Array to a Function (contd.)
Figure 11-20 XYZ Companys modified sales program (contd.)
An Introduction to Programming with C++, Seventh Edition 34
Passing a One-Dimensional Array to a Function (contd.)
Figure 11-21 Completed desk-check table for the XYZ Companys modified sales program
An Introduction to Programming with C++, Seventh Edition 35
The Moonbucks Coffee Program Calculating a Total and Average
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
An Introduction to Programming with C++, Seventh Edition
36
The Moonbucks Coffee Program (contd.)
Figure 11-22 Problem specification, IPO chart information, and C++ instructions for the Moonbucks Coffee program
An Introduction to Programming with C++, Seventh Edition 37
The Moonbucks Coffee Program (contd.)
Figure 11-22 Problem specification, IPO chart information, and C++ instructions for the Moonbucks Coffee program (contd.)
An Introduction to Programming with C++, Seventh Edition 38
The Moonbucks Coffee Program (contd.)
Figure 11-22 Problem specification, IPO chart information, and C++ instructions for the Moonbucks Coffee program (contd.)
An Introduction to Programming with C++, Seventh Edition 39
The Moonbucks Coffee Program (contd.)
Figure 11-23 Moonbucks Coffee program
An Introduction to Programming with C++, Seventh Edition 40
The Moonbucks Coffee Program (contd.)
Figure 11-23 Moonbucks Coffee program (contd.)
An Introduction to Programming with C++, Seventh Edition 41
The Moonbucks Coffee Program (contd.)
Figure 11-24 Result of running the Moonbucks Coffee program
An Introduction to Programming with C++, Seventh Edition
42
The JK Motors ProgramSearching an Array
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
An Introduction to Programming with C++, Seventh Edition
43
The JK Motors ProgramSearching an Array (contd.)
Figure 11-25 Problem specification, IPO chart information, and C++ instructions for the JK motors program
An Introduction to Programming with C++, Seventh Edition 44
The JK Motors ProgramSearching an Array (contd.)
Figure 11-25 Problem specification, IPO chart information, and C++ instructions for the JK motors program (contd.)
An Introduction to Programming with C++, Seventh Edition 45
The JK Motors ProgramSearching an Array (contd.)
Figure 11-26 JK motors program
An Introduction to Programming with C++, Seventh Edition 46
The JK Motors ProgramSearching an Array (contd.)
Figure 11-26 JK motors program (contd.)
An Introduction to Programming with C++, Seventh Edition
47
The JK Motors ProgramSearching an Array (contd.)
Figure 11-27 Sample run of the JK motors program
An Introduction to Programming with C++, Seventh Edition
48
The Hourly Rate ProgramAccessing an Individual Element
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
An Introduction to Programming with C++, Seventh Edition
49
The Hourly Rate ProgramAccessing an Individual Element (contd.)
Figure 11-28 Problem specification, IPO chart information, and C++ instructions for the hourly rate program
An Introduction to Programming with C++, Seventh Edition 50
The Hourly Rate ProgramAccessing an Individual Element (contd.)
Figure 11-28 Problem specification, IPO chart information, and C++ instructions for the hourly rate program (contd.)
An Introduction to Programming with C++, Seventh Edition 51
The Hourly Rate ProgramAccessing an Individual Element (contd.)
Figure 11-29 Hourly rate program
An Introduction to Programming with C++, Seventh Edition 52
The Hourly Rate ProgramAccessing an Individual Element (contd.)
Figure 11-30 Sample run of the hourly rate program
An Introduction to Programming with C++, Seventh Edition
53
The Random Numbers Program Finding the Highest Value
Programs 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 displays highest value
An Introduction to Programming with C++, Seventh Edition
54
The Random Numbers Program (contd.)
Figure 11-31 Problem specification, IPO chart information, and C++ instructions for the random numbers program
An Introduction to Programming with C++, Seventh Edition 55
The Random Numbers Program (contd.)
Figure 11-31 Problem specification, IPO chart information, and C++ instructions for the random numbers program (contd.)
An Introduction to Programming with C++, Seventh Edition 56
The Random Numbers Program (contd.)
Figure 11-31 Problem specification, IPO chart information, and C++ instructions for the random numbers program (contd.)
An Introduction to Programming with C++, Seventh Edition
57
The Random Numbers Program (contd.)
Figure 11-31 Problem specification, IPO chart information, and C++ instructions for the random numbers program (contd.)
An Introduction to Programming with C++, Seventh Edition 58
The Random Numbers Program (contd.)
Figure 11-32 Sample run of the random numbers program
An Introduction to Programming with C++, Seventh Edition
59
The Random Numbers Program (contd.)
Figure 11-33 Random numbers program
An Introduction to Programming with C++, Seventh Edition 60
The Random Numbers Program (contd.)
Figure 11-33 Random numbers program (contd.)
An Introduction to Programming with C++, Seventh Edition 61
The Random Numbers Program (contd.)
Figure 11-33 Random numbers program (contd.)
An Introduction to Programming with C++, Seventh Edition
62
The Random Numbers Program (contd.)
Figure 11-34 Desk-check table after the for loop on lines 24 through 26 ends
An Introduction to Programming with C++, Seventh Edition 63
The Random Numbers Program (contd.)
Figure 11-35 Desk-check table after the displayArray function header is processed
An Introduction to Programming with C++, Seventh Edition 64
The Random Numbers Program (contd.)
Figure 11-36 Desk-check table after the displayArray function ends
An Introduction to Programming with C++, Seventh Edition 65
The Random Numbers Program (contd.)
Figure 11-37 Desk-check table after the declaration statements on lines 52 and 55 are processed
An Introduction to Programming with C++, Seventh Edition 66
The Random Numbers Program (contd.)
Figure 11-38 Desk-check table showing the fourth elements value entered in the high variable
An Introduction to Programming with C++, Seventh Edition 67
The Random Numbers Program (contd.)
Figure 11-39 Completed desk-check table for random numbers program
An Introduction to Programming with C++, Seventh Edition
68
Sorting the Data Stored in a OneDimensional Array
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
An Introduction to Programming with C++, Seventh Edition
69
Sorting the Data Stored in a OneDimensional Array (contd.)
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
An Introduction to Programming with C++, Seventh Edition
70
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-40 Array values before, during, and after the bubble sort
An Introduction to Programming with C++, Seventh Edition
71
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-41 Bubble sort program
An Introduction to Programming with C++, Seventh Edition 72
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-41 Bubble sort program (contd.)
An Introduction to Programming with C++, Seventh Edition 73
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-42 Desk-check table after the declaration statements on lines 11 through 16 are processed
An Introduction to Programming with C++, Seventh Edition
74
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-43 Desk-check table after nested loop is processed first time
An Introduction to Programming with C++, Seventh Edition
75
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-44 Desk-check table after nested loop is processed second time
An Introduction to Programming with C++, Seventh Edition
76
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-45 Desk-check table after nested loop is processed third time
An Introduction to Programming with C++, Seventh Edition
77
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-46 Desk-check table after outer loop is processed first time
An Introduction to Programming with C++, Seventh Edition
78
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-47 Desk-check table after the instructions on lines 21 and 23 are processed
An Introduction to Programming with C++, Seventh Edition 79
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-48 Desk-check table after the instructions in the nested loop are processed
An Introduction to Programming with C++, Seventh Edition 80
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-49 Desk-check table after the instructions in the nested loop are processed again
An Introduction to Programming with C++, Seventh Edition 81
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-50 Current status of the desk-check table
An Introduction to Programming with C++, Seventh Edition 82
Sorting the Data Stored in a OneDimensional Array (contd.)
Figure 11-51 Result of running the bubble sort program
An Introduction to Programming with C++, Seventh Edition
83
Parallel One-Dimensional Arrays
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
An Introduction to Programming with C++, Seventh Edition
84
Parallel One-Dimensional Arrays (contd.)
Figure 11-52 Problem specification and IPO chart information for the club membership program
An Introduction to Programming with C++, Seventh Edition 85
Parallel One-Dimensional Arrays (contd.)
Figure 11-52 Problem specification and IPO chart information for the club membership program (cont.)
An Introduction to Programming with C++, Seventh Edition 86
Parallel One-Dimensional Arrays (contd.)
Figure 11-53 IPO chart information and C++ instructions for the club membership program
An Introduction to Programming with C++, Seventh Edition
87
Parallel One-Dimensional Arrays (contd.)
Figure 11-53 IPO chart information and C++ instructions for the club membership program (cont.)
An Introduction to Programming with C++, Seventh Edition
88
Parallel One-Dimensional Arrays (contd.)
Figure 11-54 Club membership program
An Introduction to Programming with C++, Seventh Edition 89
Parallel One-Dimensional Arrays (contd.)
Figure 11-54 Club membership program (contd.)
An Introduction to Programming with C++, Seventh Edition
90
Parallel One-Dimensional Arrays (contd.)
Figure 11-55 Sample run of the club membership program
An Introduction to Programming with C++, Seventh Edition
91
Summary
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
An Introduction to Programming with C++, Seventh Edition
92
Summary (contd.)
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 arrays 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
An Introduction to Programming with C++, Seventh Edition 93
Lab 11-1: Stop and Analyze
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
An Introduction to Programming with C++, Seventh Edition
94
Lab 11-2: Plan and Create
Plan and create a program for Penelope Havert
Figure 11-57 Problem specification for Lab 11-2
An Introduction to Programming with C++, Seventh Edition
95
Lab 11-3: Modify
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
An Introduction to Programming with C++, Seventh Edition
96
Lab 11-4: Desk-Check
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?
An Introduction to Programming with C++, Seventh Edition
97
Lab 11-5: Debug
Open the program in the Lab11-5.cpp file Debug the program
An Introduction to Programming with C++, Seventh Edition
98