1.

Slides:



Advertisements
Similar presentations
An Introduction to Programming with C++ Fifth Edition
Advertisements

An Introduction to Programming with C++ Fifth Edition Chapter 3 Completing the Problem-Solving Process and Getting Started with C++
Programming with Microsoft Visual Basic th Edition
An Introduction to Programming with C++ Fifth Edition Chapter 5 The Selection Structure.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Introducing Algorithms, Pseudocode and.
An Introduction to Programming with C++ Fifth Edition
An Introduction to Programming with C++ Fifth Edition
An Introduction to Programming with C++ Fifth Edition Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
An Introduction to Programming with C++ Fifth Edition Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
An Introduction to Programming with C++ Fifth Edition Chapter 8 More on the Repetition Structure.
An Introduction to Programming with C++ Fifth Edition Chapter 1 An Introduction to Programming.
Microsoft Visual Basic 2008: Reloaded Fourth Edition
Chapter 4: The Selection Structure
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Computer Programming TCP1224 Chapter 2 Beginning the Problem-Solving Process.
Chapter 12: How Long Can This Go On?
Computer Programming TCP1224 Chapter 3 Completing the Problem-Solving Process and Getting Started with C++
Input, Output, and Processing
Computer Programming TCP1224 Chapter 4 Variables, Constants, and Arithmetic Operators.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Chapter 3: Assignment, Formatting, and Interactive Input.
Computer Programming TCP1224 Chapter 5 The Selection Structure.
An Introduction to Programming with C++ Sixth Edition
An Introduction to Programming with C++ Sixth Edition Chapter 13 Strings.
Chapter 7: The Repetition Structure Introduction to Programming with C++ Fourth Edition.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
CHAPTER 3 COMPLETING THE PROBLEM- SOLVING PROCESS AND GETTING STARTED WITH C++ An Introduction to Programming with C++ Fifth Edition.
Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
An Introduction to Programming with C++1 The Selection Structure Tutorial 6.
An Introduction to Programming with C++ Sixth Edition Chapter 8 More on the Repetition Structure.
Bill Tucker Austin Community College COSC 1315
Exam 1 Review Jeff has 100 students in his MIS120 class. He is giving a 50 question exam worth 100 points. The following commands are available to you.
Chapter 9: Value-Returning Functions
Chapter Topics The Basics of a C++ Program Data Types
Topics Designing a Program Input, Processing, and Output
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
An Introduction to Programming with C++ Sixth Edition
Completing the Problem-Solving Process
Chapter 2: Input, Processing, and Output
Value-Returning Functions
Basic Elements of C++.
The Selection Structure
Chapter Topics 2.1 Designing a Program 2.2 Output, Input, and Variables 2.3 Variable Assignment and Calculations 2.4 Variable Declarations and Data Types.
User-Defined Functions
An Introduction to Programming with C++ Fifth Edition
Basic Elements of C++ Chapter 2.
Designing and Debugging Batch and Interactive COBOL Programs
Making Decisions in a Program
Introduction to C++ Programming
Objectives After studying this chapter, you should be able to:
CIS16 Application Development Programming with Visual Basic
Problem Solving.
Microsoft Visual Basic 2005: Reloaded Second Edition
Chapter 9: Value-Returning Functions
Chapter 2: Introduction to C++.
Topics Designing a Program Input, Processing, and Output
Chapter 5: Control Structures II (Repetition)
An Introduction to Programming with C++ Fifth Edition
Topics Designing a Program Input, Processing, and Output
An Introduction to Programming with C++ Fifth Edition
Chapter 2: Input, Processing, and Output
Chapter 5: The Selection Structure
Chapter 1 c++ structure C++ Input / Output
Programming Logic and Design Eighth Edition
Presentation transcript:

1

An Introduction to Programming with C++ Fifth Edition Chapter 1 An Introduction to Programming 2

Objectives 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++, Fifth Edition 3 3

Concept Lesson Programmers A Brief History of Programming Languages Control Structures Summary An Introduction to Programming with C++, Fifth Edition 4

Programmers Programs are the directions given to computers Programmers are the people who write computer programs Applications programmers write, maintain, and/or customize programs that handle a specific task Systems programmers write and maintain programs that help the computer carry out its basic operating functions An Introduction to Programming with C++, Fifth Edition 5

A Brief History of Programming Languages Programming languages are the languages used to communicate with a computer E.g., C++, C#, Java, Visual Basic, Perl, C, COBOL Types Machine languages Assembly languages High-level languages An Introduction to Programming with C++, Fifth Edition 6

Machine Languages The first programmers had to write the program instructions using only combinations of 0s and 1s E.g., 00101 10001 10000 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 is tedious and error-prone; requires highly trained programmers An Introduction to Programming with C++, Fifth Edition 7

Assembly Languages Assembly languages simplify programmer’s job Can use mnemonics instead of 0s and 1s E.g., ADD bx, ax 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++, Fifth Edition 8

High-Level Languages High-level languages allow programmer to use English-like instructions E.g., grossPay = hours * rate High-level languages are more machine-independent Programs written in a high-level language can be used on many different types of computers Compilers convert the instructions into 0s and 1s Interpreters translate the program line by line as the program is running An Introduction to Programming with C++, Fifth Edition 9

High-Level Languages (continued) 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 programmer to focus on the objects that the program can use to accomplish its goal Examples: C++, Visual Basic, Java, C# An Introduction to Programming with C++, Fifth Edition 10

Control Structures Programs are written using three basic structures Sequence Used in every program you write Repetition Used in most programs you write Selection Called control structures or logic structures An Introduction to Programming with C++, Fifth Edition 11

The Sequence Structure The sequence structure directs the computer to process the program instructions, one after another, in the order listed in the program An Introduction to Programming with C++, Fifth Edition 12

The Sequence Structure (continued) An Introduction to Programming with C++, Fifth Edition 13

The Repetition Structure Repetition structure: directs computer to repeat one or more instructions until some condition is met Also called a loop or iteration An Introduction to Programming with C++, Fifth Edition 14

The Repetition Structure (continued) An Introduction to Programming with C++, Fifth Edition 15

The Repetition Structure (continued) What could you do if you don’t know precisely how many steps separate Rob from the chair? An Introduction to Programming with C++, Fifth Edition 16

The Repetition Structure (continued) An Introduction to Programming with C++, Fifth Edition 17

The Selection Structure Selection structure: makes a decision and then takes an appropriate action based on that decision Also called the decision structure An Introduction to Programming with C++, Fifth Edition 18

The Selection Structure (continued) An Introduction to Programming with C++, Fifth Edition 19

The Selection Structure (continued) An Introduction to Programming with C++, Fifth Edition 20

Summary Programs: 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 languages High-level languages can be used to create procedure- oriented programs or object-oriented programs Algorithm: step-by-step instructions that accomplish a task (not written in a programming language) Algorithms contain one or more of the following control structures: sequence, selection, and repetition An Introduction to Programming with C++, Fifth Edition 21 21

Summary (continued) Sequence structure: process the instructions, one after another, in the order listed Repetition structure: repeat one or more instructions until some condition is met Selection structure: directs the computer to make a decision, and then to select an appropriate action based on that decision An Introduction to Programming with C++, Fifth Edition 22 22

Application Lesson: Using the Control Structures Lab 1.1: Stop and Analyze Lab 1.2: salespeople selling more than $2,000 receive 3.5% bonus; all others receive 3% bonus Lab 1.3: An Introduction to Programming with C++, Fifth Edition 23

An Introduction to Programming with C++ Fifth Edition Chapter 2 Beginning the Problem-Solving Process 24

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++, Fifth Edition 25 25

Concept Lesson Problem Solving Solving Everyday Problems Creating Computer Solutions to Problems Analyzing the Problem Planning the Algorithm Desk-Checking the Algorithm The Gas Mileage Problem Summary An Introduction to Programming with C++, Fifth Edition 26

Problem Solving In this lesson, you will: Explore the thought process followed when solving problems Learn how to use a similar process to create a computer solution to a problem Called a computer program An Introduction to Programming with C++, Fifth Edition 27

Solving Everyday Problems First step in solving a problem: analyze it E.g., problem of being hungry Next, you plan, review, implement, evaluate, and modify (if necessary) the solution E.g., if you are still hungry An Introduction to Programming with C++, Fifth Edition 28

Solving Everyday Problems (continued) An Introduction to Programming with C++, Fifth Edition 29

Solving Everyday Problems (continued) An Introduction to Programming with C++, Fifth Edition 30

Creating Computer Solutions to Problems Analysis tools: IPO charts, pseudocode, flowcharts To desk-check or hand-trace, use pencil, paper, and sample data to walk through algorithm A coded algorithm is called a program An Introduction to Programming with C++, Fifth Edition 31

Creating Computer Solutions to Problems (continued) An Introduction to Programming with C++, Fifth Edition 32

Analyzing the Problem 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++, Fifth Edition 33

Analyzing the Problem (continued) An Introduction to Programming with C++, Fifth Edition 34

IPO Charts Use an IPO chart to organize and summarize the results of a problem analysis IPO: Input, Processing, and Output An Introduction to Programming with C++, Fifth Edition 35

IPO Charts (continued) An Introduction to Programming with C++, Fifth Edition 36

IPO Charts (continued) An Introduction to Programming with C++, Fifth Edition 37

Analyzing the Problem (continued) First, reduce the amount of information you need to consider in your analysis: An Introduction to Programming with C++, Fifth Edition 38

Analyzing the Problem (continued) Worse than having too much information is not having enough information to solve problem: An Introduction to Programming with C++, Fifth Edition 39

Analyzing the Problem (continued) Distinguish between information that is missing and information that is implied: An Introduction to Programming with C++, Fifth Edition 40

Planning the Algorithm Algorithm: set of instructions that will transform the problem’s input into its output Record it in the Processing column of the IPO chart Processing item: intermediate value used by algorithm when processing input into output Pseudocode is a tool programmers use to help them plan an algorithm Short English statements An Introduction to Programming with C++, Fifth Edition 41

Planning the Algorithm (continued) An Introduction to Programming with C++, Fifth Edition 42

Planning the Algorithm (continued) Flowcharts are also used to plan an algorithm Use standardized symbols Symbols connected with flowlines Oval: start/stop symbol Rectangle: process symbol Represents tasks such as calculations Parallelogram: input/output symbol Represents I/O tasks An Introduction to Programming with C++, Fifth Edition 43

Planning the Algorithm (continued) An Introduction to Programming with C++, Fifth Edition 44

Planning the Algorithm (continued) A problem can have more than one solution: An Introduction to Programming with C++, Fifth Edition 45

Hints for Writing Algorithms This problem specification is almost identical to the one shown earlier in Figure 2-4 An Introduction to Programming with C++, Fifth Edition 46

Hints for Writing Algorithms (continued) You may use a portion of a previous solution to solve current problem An Introduction to Programming with C++, Fifth Edition 47

Desk-Checking the Algorithm An Introduction to Programming with C++, Fifth Edition 48

Desk-Checking the Algorithm (continued) An Introduction to Programming with C++, Fifth Edition 49

Desk-Checking the Algorithm (continued) Valid data is data that the programmer is expecting the user to enter Invalid data is data that he or she 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++, Fifth Edition 50

The Gas Mileage Problem An Introduction to Programming with C++, Fifth Edition 51

The Gas Mileage Problem (continued) After planning the algorithm, you desk-check it: An Introduction to Programming with C++, Fifth Edition 52

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 During analysis, you determine the output and input During planning, you write the steps that will transform the input into the output An Introduction to Programming with C++, Fifth Edition 53 53

Summary (continued) After the analysis and planning, you desk-check the algorithm Follow each of the steps in algorithm by hand Coding refers to translating the algorithm into a language that the computer can understand Before writing an algorithm, consider whether you have already solved a similar problem An Introduction to Programming with C++, Fifth Edition 54 54

Application Lesson: Using the First Steps in the Problem-Solving Process Lab 2.1: Stop and Analyze Lab 2.2: Create a program that the salesclerks can use to calculate and display the required number of rolls Lab 2.3: The program must now display the number of single and double rolls of wallpaper Lab 2.4: Desk-Check Lab Lab 2.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 55

An Introduction to Programming with C++ Fifth Edition Chapter 3 Completing the Problem-Solving Process and Getting Started with C++ 56

Objectives Code an algorithm into a program Desk-check a program Evaluate and modify a program Understand the components of a C++ program Create a C++ program An Introduction to Programming with C++, Fifth Edition 57 57

Objectives (continued) Save, build, and execute a C++ program Locate and fix an error in a C++ program Print a C++ program Make a backup copy of a solution An Introduction to Programming with C++, Fifth Edition 58 58

Concept Lesson More on the Problem-Solving Process Coding the Algorithm into a Program Desk-Checking the Program Evaluating and Modifying the Program Creating a C++ Program An Introduction to Programming with C++, Fifth Edition 59

More on the Problem-Solving Process An Introduction to Programming with C++, Fifth Edition 60

Coding the Algorithm into a Program An Introduction to Programming with C++, Fifth Edition 61

Assigning Names, Data Types, and Initial Values to the IPO Items To code algorithm, first assign a name to each input, processing, and output item in IPO chart Names can contain only letters, numbers, and _ Cannot contain punctuation characters or spaces Examples: raise newPay Each input/processing/output item must have a data type You may initialize each item usually in lowercase letters use camel case if name contains multiple words An Introduction to Programming with C++, Fifth Edition 62

Assigning Names, Data Types, and Initial Values to the IPO Items (continued) double is a keyword this is a statement all C++ statements must end with a semicolon An Introduction to Programming with C++, Fifth Edition 63

Translating the Algorithm Steps into C++ Code cout: standard output stream cin: standard input stream <<: insertion operator >>: extraction operator stream: sequence of characters, to perform standard I/O operations a stream manipulator An Introduction to Programming with C++, Fifth Edition 64

Desk-Checking the Program An Introduction to Programming with C++, Fifth Edition 65

Desk-Checking the Program (continued) An Introduction to Programming with C++, Fifth Edition 66

Desk-Checking the Program (continued) An Introduction to Programming with C++, Fifth Edition 67

Evaluating and Modifying the Program Testing is running the program, with sample data Results should agree with desk-check ones Debugging is locating/removing errors in program Program errors are called bugs A syntax error occurs if an instruction violates the programming language’s syntax (set of rules) E.g., cout < "Hello"; A logic error occurs if an instruction does not give the expected results E.g., average = number1 + number2 / 2; An Introduction to Programming with C++, Fifth Edition 68

Creating a C++ Program created using an IDE or a general-purpose editor source file: Ch3Lab2.cpp object file: Ch3Lab2.obj executable file: Ch3Lab2.exe An Introduction to Programming with C++, Fifth Edition 69

Creating a C++ Program (continued) An Introduction to Programming with C++, Fifth Edition 70

Summary Fourth step in the problem-solving process is to code the algorithm into a program In C++, you perform standard I/O operations using streams (sequences of characters) cout and cin Insertion operator (<<) sends data to output stream Extraction operator (>>) gets data from input stream After coding the algorithm, you desk-check program Final step in the problem-solving process is to evaluate and modify (if necessary) the program An Introduction to Programming with C++, Fifth Edition 71 71

Summary (continued) Some programs have errors, called bugs Syntax error occurs when an instruction violates one of the rules of the programming language’s syntax Logic error occurs when you enter an instruction that does not give you the expected results You debug to locate and remove errors To create and execute a C++ program, you need to have a text editor and a C++ compiler Compiler translates source code into object code Linker produces executable file An Introduction to Programming with C++, Fifth Edition 72 72

Summary (continued) Comments are internal documentation of programs C++ programs typically include at least one directive using statements tell compiler where it can find the definition of certain keywords A function is a block of code that performs a task main() is where the execution of program begins The first line in a function is called the header After the header comes the body, enclosed in braces An Introduction to Programming with C++, Fifth Edition 73

Application Lesson: Completing the Problem-Solving Process Lab 3.1: Stop and Analyze Lab 3.2: Use Microsoft Visual C++ 2005 Express Edition Lab 3.3: Modify the program created in Lab 3.2 so that it doesn’t use a processing item Lab 3.4: Desk-Check Lab Lab 3.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 74

Application Lesson: Completing the Problem-Solving Process (continued) An Introduction to Programming with C++, Fifth Edition 75

An Introduction to Programming with C++ Fifth Edition Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators 76

More on the Problem-Solving Process An Introduction to Programming with C++, Fifth Edition 77

Variables and Named Constants Declare a memory location for each input, processing, and output item in IPO chart A variable is a type of memory location whose contents can change while program is running Values of named constant items remain the same each time the program is executed An Introduction to Programming with C++, Fifth Edition 78

Variables and Named Constants (continued) Requires four memory locations: Two input items radius variable pi named constant One processing item radius squared One output item area An Introduction to Programming with C++, Fifth Edition 79

Selecting a Name for a Memory Location Identifiers should be descriptive and follow some rules: An Introduction to Programming with C++, Fifth Edition 80

Selecting a Name for a Memory Location (continued) Most programmers: Use uppercase letters for named constants Use lowercase letters for variables Use camel case if a variable’s name contains two or more words An Introduction to Programming with C++, Fifth Edition 81

Selecting a Name for a Memory Location (continued) An Introduction to Programming with C++, Fifth Edition 82

Selecting a Data Type for a Memory Location These data types, except string, are fundamental data types An Introduction to Programming with C++, Fifth Edition 83

Selecting a Data Type for a Memory Location (continued) string is a class Program must include: #include <string> using std::string; C++ contains one or more data types for storing Integers (whole numbers) Floating-point numbers (with a decimal place) Characters (letters, symbols, and numbers that will not be used in calculations) Boolean values (true and false) An Introduction to Programming with C++, Fifth Edition 84

Selecting a Data Type for a Memory Location (continued) The data type to use for a memory location depends on the values it will store An Introduction to Programming with C++, Fifth Edition 85

How Data is Stored in Internal Memory An Introduction to Programming with C++, Fifth Edition 86

How Data is Stored in Internal Memory (continued) An Introduction to Programming with C++, Fifth Edition 87

Selecting an Initial Value for a Memory Location To initialize is to assign an initial value to a memory location Typically a literal constant Type can be: numeric, character, or string A location with bool data type can be initialized with keywords true or false Typical initialization values 0.0 ‘ ‘ “” true, false An Introduction to Programming with C++, Fifth Edition 88

Selecting an Initial Value for a Memory Location (continued) An Introduction to Programming with C++, Fifth Edition 89

Type Conversions Implicit type conversions can occur when assigning a value to a memory location Or, when processing calculation statements Value can be promoted or demoted Implicit demotion can adversely affect output Use explicit type conversion (type casting) to convert an item from one data type to another static_cast operator An Introduction to Programming with C++, Fifth Edition 90

Type Conversions (continued) An Introduction to Programming with C++, Fifth Edition 91

Type Conversions (continued) An Introduction to Programming with C++, Fifth Edition 92

Variables and Named Constants (continued) An Introduction to Programming with C++, Fifth Edition 93

Declaring a Named Constant An Introduction to Programming with C++, Fifth Edition 94

Declaring a Variable An Introduction to Programming with C++, Fifth Edition 95

Declaring a Variable (continued) An Introduction to Programming with C++, Fifth Edition 96

Using an Assignment Statement to Store Data in a Variable An Introduction to Programming with C++, Fifth Edition 97

Using an Assignment Statement to Store Data in a Variable (continued) An Introduction to Programming with C++, Fifth Edition 98

Arithmetic Operators Precedence numbers indicate order in which computer performs the operation in an expression Use parentheses to override order of precedence An Introduction to Programming with C++, Fifth Edition 99

Arithmetic Operators (continued) An Introduction to Programming with C++, Fifth Edition 100

Arithmetic Operators (continued) An Introduction to Programming with C++, Fifth Edition 101

Arithmetic Assignment Operators An Introduction to Programming with C++, Fifth Edition 102

Getting Data from the Keyboard Use >> to get numeric, character, or string values from the keyboard and store them in a variable Stops reading characters when it encounters a white-space character in the input Blank, tab, or newline An alternative is to use getline() An Introduction to Programming with C++, Fifth Edition 103

The getline() Function When getline() encounters the delimiter character in the input, it consumes the character newline character Items between parentheses in a function’s syntax are the arguments An Introduction to Programming with C++, Fifth Edition 104

The ignore() Function ignore() instructs computer to read and consume characters entered at keyboard An Introduction to Programming with C++, Fifth Edition 105

The ignore() Function (continued) An Introduction to Programming with C++, Fifth Edition 106

Formatting Floating-Point Numbers Use fixed stream manipulator to display a floating-point number in fixed-point notation #include <iostream> using std::fixed; Use scientific stream manipulator for e notation using std::scientific; Setprecision stream manipulator controls number of decimal places displayed #include <iomanip> using std::setprecision; An Introduction to Programming with C++, Fifth Edition 107

Formatting Floating-Point Numbers (continued) An Introduction to Programming with C++, Fifth Edition 108

Formatting Floating-Point Numbers (continued) An Introduction to Programming with C++, Fifth Edition 109

Summary Programs have variables, constants (named, literal), and arithmetic operators (to perform calculations) const dataType constantName = value; dataType variableName [= initialValue]; Use assignment statement to store data in a variable variableName = expression; When assigning a value to a memory location, the value should fit the memory location’s data type Use static_cast operator to convert an item of data from one data type to another An Introduction to Programming with C++, Fifth Edition 110 110

Summary (continued) Arithmetic operators have a precedence number Use parentheses to override order of precedence Arithmetic assignment operators abbreviate an assignment statement varName arithmeticAssignmentOp expr; getline() gets a string of characters ignore() reads and consumes characters entered at the keyboard fixed and scientific stream manipulators format the display of floating-point numbers An Introduction to Programming with C++, Fifth Edition 111 111

Application Lesson: Using Variables, Constants, and Arithmetic Operators in a C++ Program Lab 4.1: Stop and Analyze Study the program shown in Figure 4-26, then answer the questions Lab 4.2: Test program in Figure 4-27 Lab 4.3: Modify program so that it allows user to enter the semester hour fee Lab 4.4: Desk-Check Lab Lab 4.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 112

An Introduction to Programming with C++ Fifth Edition Chapter 5 The Selection Structure 113

Objectives Write pseudocode for the selection structure Create a flowchart for the selection structure Code the if and if/else forms of the selection structure Write code that uses comparison operators and logical operators An Introduction to Programming with C++, Fifth Edition 114 114

Objectives (continued) Convert the contents of a char variable to uppercase or lowercase Convert the contents of a string variable to uppercase or lowercase Use the .NET ToUpper(), ToLower(), and CompareTo() methods Format numeric output in .NET An Introduction to Programming with C++, Fifth Edition 115 115

Concept Lesson Using the Selection Structure Writing Pseudocode for the if and if/else Selection Structures Flowcharting the if and if/else Selection Structures Coding the if and if/else Selection Structures An Introduction to Programming with C++, Fifth Edition 116

Concept Lesson (continued) Comparison Operators Logical Operators Comparing Characters Comparing Strings An Introduction to Programming with C++, Fifth Edition 117

Using the Selection Structure Also called the decision structure Condition specifies decision Results in either a true or false answer only Three forms: if, if/else, and switch (or case) An Introduction to Programming with C++, Fifth Edition 118

Using the Selection Structure (continued) An Introduction to Programming with C++, Fifth Edition 119

Writing Pseudocode for the if and if/else Selection Structures An Introduction to Programming with C++, Fifth Edition 120

Flowcharting the if and if/else Selection Structures selection/repetition symbol An Introduction to Programming with C++, Fifth Edition 121

Coding the if and if/else Selection Structures An Introduction to Programming with C++, Fifth Edition 122

Coding the if and if/else Selection Structures (continued) An Introduction to Programming with C++, Fifth Edition 123

Comparison Operators Often called relational operators If expression has multiple comparison operators at same precedence, it is evaluated from left to right Comparison operators are evaluated after any arithmetic operators in the expression An Introduction to Programming with C++, Fifth Edition 124

Comparison Operators (continued) An Introduction to Programming with C++, Fifth Edition 125

Comparison Operators (continued) An Introduction to Programming with C++, Fifth Edition 126

Comparison Operator Program 1: Swapping Numerical Values An Introduction to Programming with C++, Fifth Edition 127

Comparison Operator Program 1: Swapping Numerical Values (continued) An Introduction to Programming with C++, Fifth Edition 128

Comparison Operator Program 1: Swapping Numerical Values (continued) temp is a local variable An Introduction to Programming with C++, Fifth Edition 129

Comparison Operator Program 1: Swapping Numerical Values (continued) An Introduction to Programming with C++, Fifth Edition 130

Comparison Operator Program 1: Swapping Numerical Values (continued) An Introduction to Programming with C++, Fifth Edition 131

Comparison Operator Program 2: Displaying the Sum or Difference An Introduction to Programming with C++, Fifth Edition 132

Comparison Operator Program 2: Displaying the Sum or Difference (continued) An Introduction to Programming with C++, Fifth Edition 133

Comparison Operator Program 2: Displaying the Sum or Difference (continued) An Introduction to Programming with C++, Fifth Edition 134

Comparison Operator Program 2: Displaying the Sum or Difference (continued) An Introduction to Programming with C++, Fifth Edition 135

Logical Operators Logical operators allow you to combine two or more conditions into one compound condition Sometimes called Boolean operators And/Or operators are evaluated after any arithmetic or comparison operators in an expression An Introduction to Programming with C++, Fifth Edition 136

Logical Operators (continued) An Introduction to Programming with C++, Fifth Edition 137

Logical Operators (continued) use short-circuit evaluation An Introduction to Programming with C++, Fifth Edition 138

Using the Truth Tables To receive a bonus, a salesperson must be rated A and he/she must sell more than $10,000 in product rating == 'A' && sales > 10000 To send a letter to all A-rated salespeople and all B-rated salespeople rating == 'A' || rating == 'B' An Introduction to Programming with C++, Fifth Edition 139

Logical Operators (continued) An Introduction to Programming with C++, Fifth Edition 140

Logical Operators (continued) An Introduction to Programming with C++, Fifth Edition 141

Logical Operator Program: Calculating Gross Pay An Introduction to Programming with C++, Fifth Edition 142

Logical Operator Program: Calculating Gross Pay (continued) data validation An Introduction to Programming with C++, Fifth Edition 143

Logical Operator Program: Calculating Gross Pay (continued) An Introduction to Programming with C++, Fifth Edition 144

Comparing Characters Display the word “Pass” if user enters the letter P (uppercase or lowercase) Display “Fail” if user enters anything else An Introduction to Programming with C++, Fifth Edition 145

Comparing Characters (continued) An Introduction to Programming with C++, Fifth Edition 146

Comparing Characters (continued) An Introduction to Programming with C++, Fifth Edition 147

Converting a Character to Uppercase or Lowercase An Introduction to Programming with C++, Fifth Edition 148

Comparing Strings String comparisons are case-sensitive “yes”, “YES”, and “Yes” are different Before using a string in a comparison, convert it to uppercase or lowercase Use transform() An Introduction to Programming with C++, Fifth Edition 149

Converting a String to Uppercase or Lowercase #include <algorithm> using std::transform; An Introduction to Programming with C++, Fifth Edition 150

transform() Function Program: Calculating Sales Tax Calculate and display the amount of sales tax that a customer owes Tax rate is 3% of purchase price If purchase is made in Gunter County, tax rate is 3.25% An Introduction to Programming with C++, Fifth Edition 151

transform() Function Program: Calculating Sales Tax (continued) An Introduction to Programming with C++, Fifth Edition 152

transform() Function Program: Calculating Sales Tax (continued) An Introduction to Programming with C++, Fifth Edition 153

Summary The selection structure (decision structure) is one of the three programming structures Forms: if, if/else, and switch (or case) Represented by a diamond in a flowchart Use the C++ if statement to code both the if and if/else forms Condition can contain variables, constants, functions, and arithmetic, comparison, or logical operators Character and string comparisons are case sensitive Use toupper(), tolower() and transform() An Introduction to Programming with C++, Fifth Edition 154 154

Application Lesson: Using the Selection Structure in a C++ Program Lab 5.1: Stop and Analyze Lab 5.2 Create the Willow Springs Health Club program Lab 5.3 Modify program so that the if statement’s true path handles the invalid data, and its false path handles the valid data Lab 5.4: Desk-Check Lab Lab 5.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 155 155

An Introduction to Programming with C++ Fifth Edition Chapter 7 The Repetition Structure 156

Objectives Include the repetition structure in pseudocode Include the repetition structure in a flowchart Code a pretest loop using the C++ while statement Initialize and update counters and accumulators Code a pretest loop using the C++ for statement An Introduction to Programming with C++, Fifth Edition 157 157

Concept Lesson Using the Repetition Structure Pretest Loops Using the while Statement to Code a Pretest Loop An Introduction to Programming with C++, Fifth Edition 158

Concept Lesson (continued) Using Counters and Accumulators Counter-Controlled Pretest Loops Using the for Statement to Code a Pretest Loop An Introduction to Programming with C++, Fifth Edition 159

Using the Repetition Structure Repetition structure repeatedly processes (a) program instruction(s) until a condition is met Also called loop Pretest loop (also called top-driven) Condition evaluated before instructions are processed Instructions may never be processed Posttest loop (also called bottom-driven) Condition evaluated after instructions are processed Instructions within loop are always processed Most common type An Introduction to Programming with C++, Fifth Edition 160

Pretest Loops Not every problem requires a loop in its solution Most loops have a condition and a body Loop condition determines the number of times instructions within loop are processed In pretest loops, condition appears at the beginning Must result in true or false value only An Introduction to Programming with C++, Fifth Edition 161

Pretest Loops (continued) An Introduction to Programming with C++, Fifth Edition 162

Pretest Loops (continued) An Introduction to Programming with C++, Fifth Edition 163

Pretest Loops (continued) An Introduction to Programming with C++, Fifth Edition 164

Flowcharting a Pretest Loop An Introduction to Programming with C++, Fifth Edition 165

Flowcharting a Pretest Loop (continued) An Introduction to Programming with C++, Fifth Edition 166

Using the while Statement to Code a Pretest Loop An Introduction to Programming with C++, Fifth Edition 167

Using the while Statement to Code a Pretest Loop (continued) An Introduction to Programming with C++, Fifth Edition 168

Pretest Loop Example – O’Donnell Incorporated Program An Introduction to Programming with C++, Fifth Edition 169

Pretest Loop Example – O’Donnell Incorporated Program (continued) Forgetting this statement turns loop into an endless or infinite loop An Introduction to Programming with C++, Fifth Edition 170

Pretest Loop Example – O’Donnell Incorporated Program (continued) An Introduction to Programming with C++, Fifth Edition 171

Using Counters and Accumulators Counter: variable used for counting something E.g., number of employees paid in a week Accumulator: variable used for accumulating E.g., total dollar amount of a week’s payroll Initializing: assigning a beginning value to counter or accumulator Typically zero Updating (incrementing): adding a number to counter or accumulator An Introduction to Programming with C++, Fifth Edition 172

Counter and Accumulator Examples – Sales Express Program An Introduction to Programming with C++, Fifth Edition 173

Counter and Accumulator Examples – Sales Express Program (continued) An Introduction to Programming with C++, Fifth Edition 174

Counter and Accumulator Examples – Sales Express Program (continued) An Introduction to Programming with C++, Fifth Edition 175

Counter and Accumulator Examples – Sales Express Program (continued) An Introduction to Programming with C++, Fifth Edition 176

Counter-Controlled Pretest Loops In previous programs, user controls loop termination by entering a sentinel value Program can also control the termination of loop Typically, done using a counter Counter-controlled loop Example: Jasper Music Company program An Introduction to Programming with C++, Fifth Edition 177

Counter-Controlled Loop Example – Jasper Music Company Program An Introduction to Programming with C++, Fifth Edition 178

Counter-Controlled Loop Example – Jasper Music Company Program (continued) An Introduction to Programming with C++, Fifth Edition 179

Counter-Controlled Loop Example – Jasper Music Company Program (continued) An Introduction to Programming with C++, Fifth Edition 180

Using the for Statement to Code a Pretest Loop An Introduction to Programming with C++, Fifth Edition 181

Using the for Statement to Code a Pretest Loop (continued) An Introduction to Programming with C++, Fifth Edition 182

Using the for Statement to Code a Pretest Loop (continued) An Introduction to Programming with C++, Fifth Edition 183

for Statement Example 1 – Holmes Supply Program An Introduction to Programming with C++, Fifth Edition 184

for Statement Example 1 – Holmes Supply Program (continued) An Introduction to Programming with C++, Fifth Edition 185

for Statement Example 1 – Holmes Supply Program (continued) An Introduction to Programming with C++, Fifth Edition 186

for Statement Example 2 – Colfax Sales Program An Introduction to Programming with C++, Fifth Edition 187

for Statement Example 2 – Colfax Sales Program (continued) An Introduction to Programming with C++, Fifth Edition 188

for Statement Example 2 – Colfax Sales Program (continued) An Introduction to Programming with C++, Fifth Edition 189

for Statement Example 3 – Morgan Company Program An Introduction to Programming with C++, Fifth Edition 190

for Statement Example 3 – Morgan Company Program (continued) An Introduction to Programming with C++, Fifth Edition 191

for Statement Example 3 – Morgan Company Program (continued) An Introduction to Programming with C++, Fifth Edition 192

Summary Use repetition structure (loop) to repeatedly process program instruction(s) until condition is met Pretest or posttest Flowchart symbol is repetition/selection diamond Most loops have a condition and a body Sentinel value may be entered by user to end loop Priming read: input instruction above a pretest loop Counters and accumulators within loops used to calculate subtotals, totals, and averages An Introduction to Programming with C++, Fifth Edition 193 193

Application Lesson: Using the Repetition Structure in a C++ Program Lab 7.1: Stop and Analyze Lab 7.2 Create, test and verify the Professor Krelina program Lab 7.3 Modify the program created in Lab 7.2 Should allow user to enter four project scores and two test scores only Lab 7.4: Desk-Check Lab Lab 7.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 194 194

An Introduction to Programming with C++ Fifth Edition Chapter 8 More on the Repetition Structure 195

Objectives Include the posttest repetition structure in pseudocode Include the posttest repetition structure in a flowchart Code a posttest loop using the C++ do while statement Nest repetition structures An Introduction to Programming with C++, Fifth Edition 196 196

Concept Lesson Posttest Loops Coding the Posttest Loop Nested Repetition Structures An Introduction to Programming with C++, Fifth Edition 197

Posttest Loops Loops can be pretest or posttest Condition in a posttest loop is evaluated with each loop iteration Evaluation occurs after instructions within loop are processed Also called bottom-driven loops An Introduction to Programming with C++, Fifth Edition 198

Posttest Loops (continued) An Introduction to Programming with C++, Fifth Edition 199

Flowcharting a Posttest Loop Flowcharts illustrate why loops are referred to as pretest and posttest loops Repetition diamond appears at the top of a pretest loop, but at the bottom of a posttest loop An Introduction to Programming with C++, Fifth Edition 200

Flowcharting a Posttest Loop (continued) An Introduction to Programming with C++, Fifth Edition 201

Flowcharting a Posttest Loop (continued) An Introduction to Programming with C++, Fifth Edition 202

Flowcharting a Posttest Loop (continued) An Introduction to Programming with C++, Fifth Edition 203

Coding the Posttest Loop Use the while statement or the for statement to code a pretest loop in C++ Use the do while statement to code a posttest loop in C++ The loop condition must be a Boolean expression Can contain variables, constants, functions, and arithmetic/comparison/logical operators An Introduction to Programming with C++, Fifth Edition 204

Coding the Posttest Loop (continued) An Introduction to Programming with C++, Fifth Edition 205

Posttest Loop Example – O’Donnell Incorporated Program Problem description In January of each year, O’Donnell Incorporated pays a 10% bonus to each of its salespeople Bonus based on amount of sales made by salesperson during previous year Payroll clerk wants a program that calculates and displays each salesperson’s bonus amount An Introduction to Programming with C++, Fifth Edition 206

Posttest Loop Example – O’Donnell Incorporated Program (continued) An Introduction to Programming with C++, Fifth Edition 207

Posttest Loop Example – O’Donnell Incorporated Program (continued) An Introduction to Programming with C++, Fifth Edition 208

Nested Repetition Structures In a nested repetition structure, one loop (inner loop) is placed entirely within another loop (outer loop) An Introduction to Programming with C++, Fifth Edition 209

Nested Repetition Structures (continued) An Introduction to Programming with C++, Fifth Edition 210

Nested Loop Example – Max Beauty Supply Program Max Beauty Supply divides its sales territory into two regions: Region 1 and Region 2 Sales manager wants a program to enter the sales amounts for both regions, one region at a time Program should calculate the total amount sold in the current region, and display that information An Introduction to Programming with C++, Fifth Edition 211

Nested Loop Example – Max Beauty Supply Program (continued) An Introduction to Programming with C++, Fifth Edition 212

Nested Loop Example – Max Beauty Supply Program (continued) An Introduction to Programming with C++, Fifth Edition 213

Nested Loop Example – Max Beauty Supply Program (continued) An Introduction to Programming with C++, Fifth Edition 214

Nested Loop Example – Max Beauty Supply Program (continued) An Introduction to Programming with C++, Fifth Edition 215

Summary A repetition structure can be a pretest or posttest loop In a pretest loop, the loop condition is evaluated before the instructions in the loop body are processed Instructions may never be processed Use while or for statements In a posttest loop, the loop condition is evaluated after the instructions in the loop body are processed Instructions are always processed at least once Use the do while statement You can nest repetition structures An Introduction to Programming with C++, Fifth Edition 216 216

Application Lesson: Using a Nested Repetition Structure in a C++ Program Lab 8.1: Stop and Analyze Lab 8.2 Create a program that displays one or more multiplication tables for Mrs. Johnson students Lab 8.3 Modify program so it uses a posttest loop (instead of a pretest loop) to display the multiplication tables Lab 8.4: Desk-Check Lab Lab 8.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 217 217

An Introduction to Programming with C++ Fifth Edition Chapter 9 Value-Returning Functions 218

Objectives Raise a number to a power Generate random numbers Create and invoke a function that returns a value Pass information, by value, to a function An Introduction to Programming with C++, Fifth Edition 219 219

Objectives (continued) Write a function prototype Understand a variable’s scope and lifetime Use the .NET C++ Math::Pow() method Generate random integers in .NET C++ An Introduction to Programming with C++, Fifth Edition 220 220

Concept Lesson Functions Value-Returning Functions Raising a Number to a Power Generating Random Numbers Creating Program-Defined Value-Returning Functions Processing a Function An Introduction to Programming with C++, Fifth Edition 221

Functions A function is a block of code that performs a task A C++ program contains at least one function: main() Most contain many more Programmers use functions because they: Allow programmer to avoid duplicating code Allow programs to be broken into manageable tasks Functions can be categorized into: Value-returning functions Void functions An Introduction to Programming with C++, Fifth Edition 222

Value-Returning Functions A value-returning function returns precisely one value after completing its assigned task Usually returned to the statement that called function Typically, statement displays return value, uses it in a calculation, or assigns it to a variable Some value-returning functions are built into C++ E.g., getline() and toupper() An Introduction to Programming with C++, Fifth Edition 223

Raising a Number to a Power You use pow( )to raise a number to a power and return result as a double number An Introduction to Programming with C++, Fifth Edition 224

Generating Random Numbers A pseudo-random number generator produces a sequence of numbers that meet certain statistical requirements for randomness Numbers are chosen with equal probability from a finite set of numbers Chosen numbers are sufficiently random for practical purposes rand() returns an integer greater than or equal to zero and less than or equal to RAND_MAX RAND_MAX is always at least 32,767 An Introduction to Programming with C++, Fifth Edition 225

Generating Random Numbers (continued) An Introduction to Programming with C++, Fifth Edition 226

Generating Random Numbers (continued) An Introduction to Programming with C++, Fifth Edition 227

Generating Random Numbers (continued) An Introduction to Programming with C++, Fifth Edition 228

Generating Random Numbers (continued) An Introduction to Programming with C++, Fifth Edition 229

Generating Random Numbers (continued) You should initialize the random number generator in each program in which it is used Otherwise, it will generate the same series of numbers each time Use the srand() function You must provide a seed Integer that represents the starting point for the random number generator Usually use time(): returns current time as seconds elapsed since midnight January 1, 1970 An Introduction to Programming with C++, Fifth Edition 230

Generating Random Numbers (continued) An Introduction to Programming with C++, Fifth Edition 231

Random Numbers Program: Displaying Random Addition Problems Program displays five random addition problems on the screen After displaying an addition problem, it allows user to enter the answer to the problem It checks whether the user’s answer is correct “Correct!” “Sorry, the sum is X” An Introduction to Programming with C++, Fifth Edition 232

Random Numbers Program: Displaying Random Addition Problems (continued) An Introduction to Programming with C++, Fifth Edition 233

Random Numbers Program: Displaying Random Addition Problems (continued) An Introduction to Programming with C++, Fifth Edition 234

Random Numbers Program: Displaying Random Addition Problems (continued) An Introduction to Programming with C++, Fifth Edition 235

Creating Program-Defined Value-Returning Functions You can create your own value-returning functions Program-defined functions A function definition is composed of: Function header Function body An Introduction to Programming with C++, Fifth Edition 236

Creating Program-Defined Value-Returning Functions (continued) An Introduction to Programming with C++, Fifth Edition 237

Function Header Function header: first line in a function definition Does not end with a semicolon Not considered a C++ statement Begins with returnDataType Next comes the name of the function Naming rules are the same as for naming variables Name usually begins with a verb Also has an optional parameterList enclosed in () Lists data type and name of formal parameters Formal parameters store the information passed to the function when it is invoked An Introduction to Programming with C++, Fifth Edition 238

Passing Information to a Function Items passed to a function are actual arguments Can be a variable, named constant, literal constant, or keyword You can pass a variable: by value (a copy of the value is passed), or by reference (the variable address is passed) Examples calcRectangleArea(2, 3) calcRectangleArea(length, width) default pass by value An Introduction to Programming with C++, Fifth Edition 239

Function Body Function body contains instructions the function follows to perform its assigned task Begins with { and ends with } The last statement is usually return expression; expression represents the value the function returns to the statement that called it return statement alerts computer that the function has completed its task Data type of expression must agree with the returnDataType specified in function header An Introduction to Programming with C++, Fifth Edition 240

Using a Function Prototype If a function definition appears below main(), you must enter a function prototype above main() Prototype specifies function’s name, data type of return value and of each formal parameter Usually after #includes and usings An Introduction to Programming with C++, Fifth Edition 241

Processing a Function When the computer processes a statement containing a program-defined function: It locates the function’s code Passes values of actual arguments to function Function receives values and stores them in the memory locations listed in its parameterList Function code is processed Return value is returned to calling function An Introduction to Programming with C++, Fifth Edition 242

Processing a Function (continued) An Introduction to Programming with C++, Fifth Edition 243

Processing a Function (continued) An Introduction to Programming with C++, Fifth Edition 244

Processing a Function (continued) An Introduction to Programming with C++, Fifth Edition 245

Processing a Function (continued) An Introduction to Programming with C++, Fifth Edition 246

The Scope and Lifetime of a Variable A variable’s scope indicates where in the program it can be used Local or global Local variables are declared within a function or appear in a function’s parameterList Global variables are declared outside of any function and remain in memory until program ends Avoid using global variables in your programs A variable’s lifetime indicates how long it remains in memory An Introduction to Programming with C++, Fifth Edition 247

The Bonus Calculation Program Program calculates and displays a 5% bonus amount Based on the amount of sales entered by the user Program uses two value-returning functions: getSales() calcBonus() An Introduction to Programming with C++, Fifth Edition 248

The Bonus Calculation Program (continued) An Introduction to Programming with C++, Fifth Edition 249

The Bonus Calculation Program (continued) An Introduction to Programming with C++, Fifth Edition 250

The Bonus Calculation Program (continued) An Introduction to Programming with C++, Fifth Edition 251

The Bonus Calculation Program (continued) An Introduction to Programming with C++, Fifth Edition 252

The Bonus Calculation Program (continued) An Introduction to Programming with C++, Fifth Edition 253

The Bonus Calculation Program (continued) An Introduction to Programming with C++, Fifth Edition 254

Summary Programmers use functions because they: Allow programmer to avoid duplicating code Allow programs to be broken into manageable tasks Functions can be value-returning or void E.g., pow() and rand() are value-returning functions A function definition has a function header and a body Header specifies return data type, function name, and (optional) parameterList enclosed in parentheses By default, variables are passed to a function by value An Introduction to Programming with C++, Fifth Edition 255 255

Summary (continued) The function body contains instructions for a task Enclosed in braces You must include a function prototype for each function defined below main() A variable’s scope can be either local or global Indicates where in a program a variable can be used If multiple memory locations have same name, and it appears in a statement, the computer uses the position of the statement within the program to determine which memory location to use An Introduction to Programming with C++, Fifth Edition 256 256

Application Lesson: Using Value-Returning Functions in a C++ Program Lab 9.1: Stop and Analyze Lab 9.2: Create a program to calculate and display the monthly payments of a loan Lab 9.3: Modified program should allow user to enter interest rates either as a whole or as a decimal number Lab 9.4: Desk-Check Lab Lab 9.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 257

An Introduction to Programming with C++ Fifth Edition Chapter 10 Void Functions 258

Objectives Create a function that does not return a value Invoke a function that does not return a value Pass information, by reference, to a function Use void functions in a .NET C++ program An Introduction to Programming with C++, Fifth Edition 259 259

Concept Lesson More About Functions Creating Void Functions Passing Variables to a Function Passing Variables By Value and By Reference An Introduction to Programming with C++, Fifth Edition 260

More About Functions Use functions to avoid duplicating code They also allow large and complex programs to be broken into small and manageable tasks main() is typically responsible for invoking each of the other functions when needed Program-defined functions streamline main() Functions can be: Value-returning Void An Introduction to Programming with C++, Fifth Edition 261

Creating Void Functions Void functions do not return a value after completing their assigned tasks E.g., to display information (such as a title and column headings) at the top of each page in a report Avoids repeating code several times in program An Introduction to Programming with C++, Fifth Edition 262

Creating Void Functions (continued) An Introduction to Programming with C++, Fifth Edition 263

Passing Variables to a Function A variable has both a value and a unique address (memory location) You can pass either the variable’s value or its address to the receiving function Pass by value Pass by reference An Introduction to Programming with C++, Fifth Edition 264

Passing Variables By Value In a pass by value, the computer passes the contents of the variable to the receiving function Receiving function is not given access to the variable in memory It cannot change value stored inside variable By default, variables are passed by value in C++ An Introduction to Programming with C++, Fifth Edition 265

Passing Variables By Value (continued) An Introduction to Programming with C++, Fifth Edition 266

Passing Variables By Value (continued) An Introduction to Programming with C++, Fifth Edition 267

Passing Variables By Value (continued) An Introduction to Programming with C++, Fifth Edition 268

Passing Variables By Value (continued) An Introduction to Programming with C++, Fifth Edition 269

Passing Variables By Value (continued) An Introduction to Programming with C++, Fifth Edition 270

Passing Variables By Reference Passing a variable’s address is referred to as passing by reference Receiving function has access to passed variable Use when you want receiving function to change contents of variable To pass a variable by reference in C++ Include an & before the name of the corresponding formal parameter in receiving function’s header Called the address-of operator An Introduction to Programming with C++, Fifth Edition 271

Passing Variables By Reference (continued) An Introduction to Programming with C++, Fifth Edition 272

Passing Variables By Reference (continued) An Introduction to Programming with C++, Fifth Edition 273

Passing Variables By Reference (continued) An Introduction to Programming with C++, Fifth Edition 274

Passing Variables By Reference (continued) An Introduction to Programming with C++, Fifth Edition 275

Passing Variables By Reference (continued) An Introduction to Programming with C++, Fifth Edition 276

Passing Variables By Value and By Reference You can mix the way variables are passed when a function is called, passing some by reference and others by value Program in Figure 10-15 allows user to enter an employee’s current salary and raise rate It then calculates and displays the employee’s raise and new salary amounts An Introduction to Programming with C++, Fifth Edition 277

Passing Variables By Value and By Reference (continued) An Introduction to Programming with C++, Fifth Edition 278

Passing Variables By Value and By Reference (continued) An Introduction to Programming with C++, Fifth Edition 279

Passing Variables By Value and By Reference (continued) An Introduction to Programming with C++, Fifth Edition 280

Passing Variables By Value and By Reference (continued) An Introduction to Programming with C++, Fifth Edition 281

Summary Functions can be: Value-returning Void Function header begins with void Pass by value: value stored inside variable is passed to receiving function Pass by reference: variable’s address in memory is passed to receiving function Receiving function can change variable’s contents Use & before corresponding formal parameter An Introduction to Programming with C++, Fifth Edition 282 282

Application Lesson: Using Void Functions in a C++ Program Lab 10.1: Stop and Analyze Lab 10.2 Create program to calculate customer’s water bill Lab 10.3 Modified program will use two void functions (rather than one void function) to calculate the number of gallons used and the water charge Lab 10.4: Desk-Check Lab Lab 10.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 283 283

An Introduction to Programming with C++ Fifth Edition Chapter 11 Arrays 284

Objectives Declare and initialize a one-dimensional array Manipulate a one-dimensional array Explain the bubble sort algorithm Pass a one-dimensional array to a function Use parallel one-dimensional arrays An Introduction to Programming with C++, Fifth Edition 285 285

Objectives (continued) Declare and initialize a two-dimensional array Enter data into a two-dimensional array Search a two-dimensional array Utilize a one-dimensional array in a .NET C++ program An Introduction to Programming with C++, Fifth Edition 286 286

Concept Lesson Using Arrays One-Dimensional Arrays Storing Data in a One-Dimensional Array Manipulating One-Dimensional Arrays Passing a One-Dimensional Array to a Function An Introduction to Programming with C++, Fifth Edition 287

Concept Lesson (continued) Using Parallel One-Dimensional Arrays Two-Dimensional Arrays Storing Data in a Two-Dimensional Array Searching a Two-Dimensional Array An Introduction to Programming with C++, Fifth Edition 288

Using Arrays Simple variable is unrelated to other variables in computer’s internal memory Also called a scalar variable Array is a group of variables Same name and data type Variables are related in some way Most commonly used One-dimensional Three-dimensional An Introduction to Programming with C++, Fifth Edition 289

One-Dimensional Arrays Visualize a one-dimensional array as a column of variables Subscript (or index) identifies each variable Indicates the variable’s position in the array Subscript of first variable is 0 Begin by populating the array so it does not contain garbage Element An Introduction to Programming with C++, Fifth Edition 290

One-Dimensional Arrays (continued) An Introduction to Programming with C++, Fifth Edition 291

Storing Data in a One-Dimensional Array Can use an assignment statement to enter data into an array See Figure 11-3 Can use >> and getline() See Figure 11-4 An Introduction to Programming with C++, Fifth Edition 292

Storing Data in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 293

Storing Data in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 294

Storing Data in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 295

Manipulating One-Dimensional Arrays Common array manipulation functions Display the contents of an array Access an array element using its subscript Search an array Calculate the average of the data stored in an array Find the highest value stored in an array Update the array elements Sort the array elements using bubble sort An Introduction to Programming with C++, Fifth Edition 296

Displaying the Contents of a One-Dimensional Array Function may need simply to display the contents of an array An Introduction to Programming with C++, Fifth Edition 297

Displaying the Contents of a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 298

Using the Subscript to Access an Element in a One-Dimensional Array Before accessing element, verify if subscript is valid An Introduction to Programming with C++, Fifth Edition 299

Searching a One-Dimensional Array Sales manager wants to determine the number of salespeople selling above a specific amount Function searches the sales array Array contains amount sold by each salesperson Look for values greater than the amount provided by sales manager An Introduction to Programming with C++, Fifth Edition 300

Searching a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 301

Calculating the Average Amount Stored in a One-Dimensional Numeric Array Prof. Jeremiah wants to calculate and display average test score earned by students on final Function adds test scores that are stored in array Then, divide sum by number of elements An Introduction to Programming with C++, Fifth Edition 302

Calculating the Average Amount Stored in a One-Dimensional Numeric Array (continued) An Introduction to Programming with C++, Fifth Edition 303

Determining the Highest Value Stored in a One-Dimensional Array Sharon Johnson keeps track of the amount of money she earns each week Function displays highest amount earned in a week Stores pay amounts in a one-dimensional array An Introduction to Programming with C++, Fifth Edition 304

Determining the Highest Value Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 305

Updating the Values Stored in a One-Dimensional Array Sales manager at Jillian Company wants a function that increases the price of each item company sells Function stores prices in a one-dimensional array Then, increase value stored in each element Also, display each item’s new price on screen An Introduction to Programming with C++, Fifth Edition 306

Updating the Values Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 307

Sorting the Values Stored in a One-Dimensional Array Arranging data in a specific order is called sorting Ascending or descending order Bubble sort is quick and easy (for small arrays) Adjacent elements that are out of order are swapped An Introduction to Programming with C++, Fifth Edition 308

Sorting the Values Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 309

Sorting the Values Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 310

Sorting the Values Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 311

Sorting the Values Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 312

Sorting the Values Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 313

Sorting the Values Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 314

Sorting the Values Stored in a One-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 315

Passing a One-Dimensional Array to a Function By default, scalar variables are passed by value To pass by reference, use address-of (&) operator Arrays in C++ are passed by reference More efficient Address of first element is passed to function Address-of operator is not used An Introduction to Programming with C++, Fifth Edition 316

Passing a One-Dimensional Array to a Function (continued) An Introduction to Programming with C++, Fifth Edition 317

Using Parallel One-Dimensional Arrays Takoda Tapahe wants a program that displays the price of the item whose product ID she enters An Introduction to Programming with C++, Fifth Edition 318

Using Parallel One-Dimensional Arrays (continued) Parallel arrays are two or more arrays whose elements are related by their position in the arrays Related by their subscript An Introduction to Programming with C++, Fifth Edition 319

Using Parallel One-Dimensional Arrays (continued) An Introduction to Programming with C++, Fifth Edition 320

Using Parallel One-Dimensional Arrays (continued) An Introduction to Programming with C++, Fifth Edition 321

Two-Dimensional Arrays Two-dimensional array resembles a table Elements are in rows and columns Each element is identified by two subscripts Subscripts specify the variable’s row and column position in the array An Introduction to Programming with C++, Fifth Edition 322

Two-Dimensional Arrays (continued) An Introduction to Programming with C++, Fifth Edition 323

Two-Dimensional Arrays (continued) An Introduction to Programming with C++, Fifth Edition 324

Storing Data in a Two-Dimensional Array You can use an assignment statement to enter data into a two-dimensional array Or use >> and getline() Use two loops to access every element in a two- dimensional array One loop tracks row subscript Other loop tracks column subscript An Introduction to Programming with C++, Fifth Edition 325

Storing Data in a Two-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 326

Storing Data in a Two-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 327

Storing Data in a Two-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 328

Searching a Two-Dimensional Array Two one-dimensional (parallel) arrays can be replaced with one two-dimensional array An Introduction to Programming with C++, Fifth Edition 329

Searching a Two-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 330

Searching a Two-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 331

Searching a Two-Dimensional Array (continued) An Introduction to Programming with C++, Fifth Edition 332

Summary An array is a group of variables that have the same name and data type and are related in some way One-dimensional Visualize as a column of variables Two-dimensional Visualize as a table You must declare an array before you can use it Each elements in a one-dimensional array is assigned a subscript First element has subscript 0 An Introduction to Programming with C++, Fifth Edition 333 333

Summary (continued) Parallel arrays are two or more arrays whose elements are related by their subscript in the arrays To create a two-dimensional array specify the number of rows and columns Each element is identified by two subscripts First subscript represents the element’s row location Second subscript represents its column location Use two loops to access every element in a two- dimensional array An Introduction to Programming with C++, Fifth Edition 334 334

Application Lesson: Using Arrays in a C++ Program Lab 11.1: Stop and Analyze Lab 11.2 Program should either display the monthly rainfall amounts on the screen or calculate and display the total rainfall amount Lab 11.3 Modified program will use a value-returning function, calcTotal(), to calculate the total rainfall amount Lab 11.4: Desk-Check Lab Lab 11.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 335

An Introduction to Programming with C++ Fifth Edition Chapter 12 String Manipulation 336

Objectives Determine the number of characters contained in a string Remove characters from a string Access characters contained in a string Replace characters in a string Insert characters within a string An Introduction to Programming with C++, Fifth Edition 337 337

Objectives (continued) Search a string for another string Compare a portion of a string variable’s contents to another string Duplicate a character within a string variable Concatenate strings Perform string manipulation in .NET C++ An Introduction to Programming with C++, Fifth Edition 338 338

Concept Lesson Manipulating Strings Determining the Number of Characters Contained in a String Removing Characters from a String Accessing Characters Contained in a String Replacing Characters in a String An Introduction to Programming with C++, Fifth Edition 339

Concept Lesson (continued) Inserting Characters within a String Searching a String Comparing a Portion of a String with Another String Duplicating a Character within a String Variable Concatenating Strings An Introduction to Programming with C++, Fifth Edition 340

Manipulating Strings Programs often need to manipulate string data For example Verify that an inventory part number begins with a specific letter Determine whether the last three characters in an employee number are valid An Introduction to Programming with C++, Fifth Edition 341

Determining the Number of Characters Contained in a String Use length() to determine the number of characters in a string variable Or use size() Syntax: string.size() An Introduction to Programming with C++, Fifth Edition 342

Determining the Number of Characters Contained in a String (continued) An Introduction to Programming with C++, Fifth Edition 343

Determining the Number of Characters Contained in a String (continued) An Introduction to Programming with C++, Fifth Edition 344

Removing Characters from a String Use erase() to remove one or more characters located anywhere in a string variable Syntax in Figure 12-2 subscript and count arguments can be numeric literal constants or the names of numeric variables An Introduction to Programming with C++, Fifth Edition 345

Removing Characters from a String (continued) An Introduction to Programming with C++, Fifth Edition 346

Accessing Characters Contained in a String You may need to determine whether a specific letter appears as the third character in a string Or, you may need to display only the string’s first five characters Use substr() to access any number of characters contained in a string variable “substr” stands for “substring” An Introduction to Programming with C++, Fifth Edition 347

Accessing Characters Contained in a String (continued) An Introduction to Programming with C++, Fifth Edition 348

Accessing Characters Contained in a String (continued) An Introduction to Programming with C++, Fifth Edition 349

Replacing Characters in a String Use replace() to replace a sequence of characters in a string variable with another sequence of characters Syntax in Figure 12-4 replacementString can be a string literal constant or the name of a string variable An Introduction to Programming with C++, Fifth Edition 350

Replacing Characters in a String (continued) An Introduction to Programming with C++, Fifth Edition 351

Inserting Characters within a String insert() inserts characters within a string An Introduction to Programming with C++, Fifth Edition 352

Searching a String Use find() to search a string variable to determine if it contains a sequence of characters An Introduction to Programming with C++, Fifth Edition 353

Searching a String (continued) An Introduction to Programming with C++, Fifth Edition 354

Comparing a Portion of a String with Another String Use the comparison operators to compare strings >, >=, <, <=, ==, and != E.g., while (name != "DONE") To compare a portion of one string with another string, use compare() An Introduction to Programming with C++, Fifth Edition 355

Comparing a Portion of a String with Another String (continued) An Introduction to Programming with C++, Fifth Edition 356

Comparing a Portion of a String with Another String (continued) An Introduction to Programming with C++, Fifth Edition 357

Duplicating a Character within a String Variable Use assign() to duplicate a character a specified number of times An Introduction to Programming with C++, Fifth Edition 358

Duplicating a Character within a String Variable (continued) An Introduction to Programming with C++, Fifth Edition 359

Concatenating Strings Connecting (or linking) strings together is called concatenating In C++, you concatenate strings using the concatenation operator The + sign An Introduction to Programming with C++, Fifth Edition 360

Concatenating Strings (continued) It is easier to use: hyphens.assign(5, '-'); An Introduction to Programming with C++, Fifth Edition 361

Summary String manipulation is a common programming task An Introduction to Programming with C++, Fifth Edition 362 362

Summary (continued) An Introduction to Programming with C++, Fifth Edition 363 363

Application Lesson: Using String Manipulation in a C++ Program Lab 12.1: Stop and Analyze Lab 12.2 Program that allows two students to play a simplified version of the Hangman Game on the computer Lab 12.3 Modify program so that it allows player 1 to enter a word of any length Lab 12.4: Desk-Check Lab Lab 12.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 364

An Introduction to Programming with C++ Fifth Edition Chapter 13 Sequential Access Files 365

Objectives Open a sequential access file Determine whether a file was opened successfully Write data to a sequential access file Read data from a sequential access file An Introduction to Programming with C++, Fifth Edition 366 366

Objectives (continued) Test for the end of a sequential access file Close a sequential access file Read information from and write information to a sequential access file in .NET C++ An Introduction to Programming with C++, Fifth Edition 367 367

Concept Lesson File Types Using Sequential Access Files Creating and Opening a Sequential Access File Determining whether a File was Opened Successfully An Introduction to Programming with C++, Fifth Edition 368

Concept Lesson (continued) Writing Information to a Sequential Access File Reading Information from a Sequential Access File Testing for the End of a Sequential Access File Closing a Sequential Access File An Introduction to Programming with C++, Fifth Edition 369

File Types A program can “read” from or “write” to a file Files to which information is written are output files Files that are read by the computer are input files Types of files in C++ Sequential Information is accessed in consecutive order Random Can be accessed in consecutive or in random order Binary Information can be accessed by its byte location An Introduction to Programming with C++, Fifth Edition 370

Using Sequential Access Files A sequential access file is often called a text file An Introduction to Programming with C++, Fifth Edition 371

Using Sequential Access Files (continued) An Introduction to Programming with C++, Fifth Edition 372

Creating and Opening a Sequential Access File You must create the input and output file objects used in a program #include <fstream> ifstream and ofstream classes using std::ifstream; and using std::ios; An Introduction to Programming with C++, Fifth Edition 373

Creating and Opening a Sequential Access File (continued) An Introduction to Programming with C++, Fifth Edition 374

Creating and Opening a Sequential Access File (continued) An Introduction to Programming with C++, Fifth Edition 375

Creating and Opening a Sequential Access File (continued) An Introduction to Programming with C++, Fifth Edition 376

Determining whether a File was Opened Successfully open() may fail when attempting to open a file E.g., it will not be able to create an output file when the path in fileName does not exist, or when the disk is full An Introduction to Programming with C++, Fifth Edition 377

Determining whether a File was Opened Successfully (continued) ! is the Not logical operator An Introduction to Programming with C++, Fifth Edition 378

Writing Information to a Sequential Access File Field: single item of information about a person, place, or thing E.g., a name, a salary, a SSN, or a price Record: a collection of one or more related fields Contains data about a specific person, place, or thing The college you are attending keeps student records Examples of fields include your SSN, name, address, phone number, credits earned, and grades earned An Introduction to Programming with C++, Fifth Edition 379

Writing Information to a Sequential Access File (continued) An Introduction to Programming with C++, Fifth Edition 380

Writing Information to a Sequential Access File (continued) To verify if information was written correctly, open the (sequential access) file in a text editor E.g., the text editor in Visual C++ or Notepad An Introduction to Programming with C++, Fifth Edition 381

Reading Information from a Sequential Access File Use >> to read char and numeric data from a file Use getline() to read string data from a sequential access file The default delimiter character is the newline character (‘\n’) An Introduction to Programming with C++, Fifth Edition 382

Reading Information from a Sequential Access File (continued) An Introduction to Programming with C++, Fifth Edition 383

Testing for the End of a Sequential Access File A file pointer keeps track of the next character either to read from or write to a file When a sequential access file is opened for input, the file pointer is positioned before the first character As characters are read, the pointer is moved forward An Introduction to Programming with C++, Fifth Edition 384

Testing for the End of a Sequential Access File (continued) An Introduction to Programming with C++, Fifth Edition 385

Closing a Sequential Access File To prevent the loss of data, close a sequential access file as soon as program finishes using it An Introduction to Programming with C++, Fifth Edition 386

Summary Sequential access files can be input or output files To use a text file, program must contain: include <fstream> directive using std::ios; statement Use the ifstream and ofstream classes to create input and output file objects, respectively Use is_open() to determine whether a text file was opened successfully An Introduction to Programming with C++, Fifth Edition 387 387

Summary (continued) Records in a text file are usually written on a separate line in the file Use endl eof() determines if file pointer is at end of the file Use close() to close a file Failing to close an open file can result in loss of data An Introduction to Programming with C++, Fifth Edition 388 388

Application Lesson: Using a Sequential Access File in a C++ Program Lab 13.1: Stop and Analyze Lab 13.2 Program should allow flower shop owner to save in a text file each salesperson’s name and sales amount Also, display the total of the sales amounts in file Lab 13.3 Modified program will allow the user to display contents of sales.txt file Lab 13.4: Desk-Check Lab Lab 13.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 389

An Introduction to Programming with C++ Fifth Edition Chapter 14 Classes and Objects 390

Objectives Differentiate between procedure-oriented and object-oriented programming Define the terms used in object-oriented programming Create a class definition Instantiate an object from a class that you define An Introduction to Programming with C++, Fifth Edition 391 391

Objectives (continued) Create a default constructor Create a parameterized constructor Include methods other than constructors in a class Overload the methods in a class An Introduction to Programming with C++, Fifth Edition 392 392

Concept Lesson Object-Oriented Programming Defining a Class in C++ Instantiating an Object An Introduction to Programming with C++, Fifth Edition 393

Concept Lesson (continued) Example 1—Using a Class that Contains Public Data Members Only Example 2—Using a Class that Contains a Private Data Member and Public Member Methods Example 3—Using a Class that Contains Two Constructors Example 4—Using a Class that Contains Overloaded Methods An Introduction to Programming with C++, Fifth Edition 394

Object-Oriented Programming OOP stands for object-oriented programming OOD stands for object-oriented design Object: anything that can be seen/touched/used E.g., check boxes, list boxes, and buttons Objects have attributes and behaviors Attributes describe the object Behaviors are operations that the object is capable of performing, or to which the object can respond Class: pattern/blueprint used to create an object Every object is an instance of some class An Introduction to Programming with C++, Fifth Edition 395

Object-Oriented Programming (continued) Abstraction means hiding the internal details of an object from the user Attributes may be hidden or exposed to user Polymorphism allows the same instruction to be carried out differently depending on the object Inheritance means you can create one class from another class Derived class inherits from base class A class encapsulates the attributes and behaviors that describe the object the class creates APIE An Introduction to Programming with C++, Fifth Edition 396

Object-Oriented Programming (continued) An Introduction to Programming with C++, Fifth Edition 397

Defining a Class in C++ Specify attributes and behaviors using a class definition Declaration section contains the class statement Naming convention uses Pascal case E.g. FormattedDate (optional) implementation section contains one definition for each prototype listed in declaration A method is a function defined in a class definition Public members come below keyword public Private members come below keyword private An Introduction to Programming with C++, Fifth Edition 398

Defining a Class in C++ (continued) An Introduction to Programming with C++, Fifth Edition 399

Defining a Class in C++ (continued) An Introduction to Programming with C++, Fifth Edition 400

Instantiating an Object After an object has been instantiated, refer to a public member using objectName.publicMember reportDate.setDate(month, day, year) An Introduction to Programming with C++, Fifth Edition 401

Example 1—Using a Class that Contains Public Data Members Only Sweets Unlimited employs several salespeople Program allows user to enter a salesperson’s name and sales amount Then, calculates salesperson’s bonus 5% of his/her sales amount Next, save name, amount, and bonus in salesInfo.txt An Introduction to Programming with C++, Fifth Edition 402

Example 1—Using a Class that Contains Public Data Members Only (continued) An Introduction to Programming with C++, Fifth Edition 403

Example 1—Using a Class that Contains Public Data Members Only (continued) An Introduction to Programming with C++, Fifth Edition 404

Example 1—Using a Class that Contains Public Data Members Only (continued) An Introduction to Programming with C++, Fifth Edition 405

Header Files Class definitions usually placed in a header file E.g., Salesperson.h #include directive tells compiler to include the contents of header file in program #include "Salesperson.h" " " indicates that header file is located in the same folder as the program file #include <iostream> < > indicates that header file is located in the folder that contains the C++ Standard Library header files An Introduction to Programming with C++, Fifth Edition 406

Header Files (continued) An Introduction to Programming with C++, Fifth Edition 407

Header Files (continued) An Introduction to Programming with C++, Fifth Edition 408

Header Files (continued) An Introduction to Programming with C++, Fifth Edition 409

Example 2—Using a Class that Contains a Private Data Member and Public Member Methods A Square object has one attribute Length of one of its sides A Square object has four behaviors Initialize its side measurement when created Assign a value to its side measurement after it has been created Provide its side measurement value Calculate and return its area An Introduction to Programming with C++, Fifth Edition 410

Example 2—Using a Class that Contains a Private Data Member and Public Member Methods (continued) An Introduction to Programming with C++, Fifth Edition 411

Example 2—Using a Class that Contains a Private Data Member and Public Member Methods (continued) An Introduction to Programming with C++, Fifth Edition 412

Example 2—Using a Class that Contains a Private Data Member and Public Member Methods (continued) Constructor: method automatically processed when object is instantiated Initializes class’s private variables A class should have at least one constructor Constructors have the same name as the class, but formal parameters (if any) differ A constructor that has no formal parameters is called the default constructor E.g., Square::Square() An Introduction to Programming with C++, Fifth Edition 413

Example 2—Using a Class that Contains a Private Data Member and Public Member Methods (continued) An Introduction to Programming with C++, Fifth Edition 414

Example 2—Using a Class that Contains a Private Data Member and Public Member Methods (continued) An Introduction to Programming with C++, Fifth Edition 415

Example 3—Using a Class that Contains Two Constructors A MonthDay object has two attributes A month number A day number A MonthDay object has three behaviors Initialize its attributes using values provided by the class Initialize its attributes using values provided by the program in which it is instantiated Return its month number and day number attributes, separated by a slash An Introduction to Programming with C++, Fifth Edition 416

Example 3—Using a Class that Contains Two Constructors (continued) An Introduction to Programming with C++, Fifth Edition 417

Example 3—Using a Class that Contains Two Constructors (continued) An Introduction to Programming with C++, Fifth Edition 418

Example 3—Using a Class that Contains Two Constructors (continued) An Introduction to Programming with C++, Fifth Edition 419

Example 3—Using a Class that Contains Two Constructors (continued) An Introduction to Programming with C++, Fifth Edition 420

Example 3—Using a Class that Contains Two Constructors (continued) Constructors that contain parameters are called parameterized constructors The method name combined with its optional parameterList is called the method’s signature An Introduction to Programming with C++, Fifth Edition 421

Example 4—Using a Class that Contains Overloaded Methods A GrossPay object has two behaviors Calculate and return the gross pay for a salaried employee Dividing the employee’s annual salary by 24 Calculate and return the gross pay for an hourly employee Multiplying the number of hours the employee worked during the week by his or her pay rate When two or more methods have the same name but different parameterLists, they are overloaded An Introduction to Programming with C++, Fifth Edition 422

Example 4—Using a Class that Contains Overloaded Methods (continued) An Introduction to Programming with C++, Fifth Edition 423

Example 4—Using a Class that Contains Overloaded Methods (continued) An Introduction to Programming with C++, Fifth Edition 424

Example 4—Using a Class that Contains Overloaded Methods (continued) An Introduction to Programming with C++, Fifth Edition 425

Example 4—Using a Class that Contains Overloaded Methods (continued) An Introduction to Programming with C++, Fifth Edition 426

Summary A class is a pattern for creating instances of the class Each instance is an object A class encapsulates object’s attributes and behaviors Abstraction means hiding an object’s internal details from the user Polymorphism allows the same instruction to be carried out differently depending on the object Use a class definition to create a class Create an object with the syntax: className objectName; An Introduction to Programming with C++, Fifth Edition 427 427

Summary (continued) Most C++ programmers enter class definitions in header files Use a constructor to initialize the data members in a class when an object is created Class can have more than one constructor Name is the same, formal parameters differ Can overload the methods in a class Allows you to use the same name for methods that require different information to perform the same task An Introduction to Programming with C++, Fifth Edition 428 428

Application Lesson: Using Classes and Objects in a C++ Program Lab 14.1: Stop and Analyze Lab 14.2 Program estimates cost of laying sod on a rectangular piece of land Lab 14.3 Modified class will contain another setDimensions() method, which can accept two integers rather than two double numbers Lab 14.4: Desk-Check Lab Lab 14.5: Debugging Lab An Introduction to Programming with C++, Fifth Edition 429