computer programme

profileo5d3g8s44
CProgrammingPowerpoints.zip

9781337117562_ppt_ch01.pptx

Chapter 1

An Overview of Computers and Programming Languages

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

Objectives (1 of 2)

In this chapter, you will:

Learn about different types of computers

Explore the hardware and software components of a computer system

Learn about the language of a computer

Learn about the evolution of programming languages

Examine high-level programming languages

Discover what a compiler is and what it does

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

Objectives (2 of 2)

Examine a C++ program

Explore how a C++ program is processed

Learn what an algorithm is and explore problem-solving techniques

Become aware of structured design and object-oriented design programming methodologies

Become aware of Standard C++, ANSI/ISO Standard C++, C++11, and C++14

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

Introduction

Without software, a computer is useless

Software is developed with programming languages

C++ is a programming language

C++ is suited for a wide variety of programming tasks

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

4

A Brief Overview of the History of Computers (1 of 3)

Early calculation devices

Abacus

Pascaline

Leibniz device

Jacquard’s weaving looms

Babbage machines: difference and analytic engines

Hollerith machine

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

5

A Brief Overview of the History of Computers (2 of 3)

Early computer-like machines

Mark I

Electronic Numerical Integrator and Calculator (ENIAC)

Von Neumann architecture

Universal Automatic Computer (UNIVAC)

Transistors and microprocessors

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

6

A Brief Overview of the History of Computers (3 of 3)

Categories of computers

Mainframe computers

Midsize computers

Micro computers (personal computers)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

7

Elements of a Computer System

Two main components

Hardware

Software

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

8

Hardware

Central processing unit (CPU)

Main memory (MM) or random access memory (RAM)

Secondary storage

Input/output devices

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

9

Central Processing Unit and Main Memory (1 of 4)

Central processing unit

Brain of the computer

Most expensive piece of hardware

Operations

Carries out arithmetic and logical operations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

10

Central Processing Unit and Main Memory (2 of 4)

FIGURE 1-1 Hardware components of a computer and main memory

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

11

Central Processing Unit and Main Memory (3 of 4)

Random access memory (or main memory) is directly connected to the CPU

All programs must be loaded into main memory before they can be executed

All data must be brought into main memory before it can be manipulated

When computer power is turned off, everything in main memory is lost

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

12

Central Processing Unit and Main Memory (4 of 4)

Main memory is an ordered sequence of memory cells

Each cell has a unique location in main memory, called the address of the cell

Each cell can contain either a programming instruction or data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

13

Secondary Storage

Secondary storage: device that stores information permanently

Examples of secondary storage

Hard disks

Flash drives

CD-ROMs

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

14

Input/Output Devices

Input devices feed data and programs into computers

Keyboard

Mouse

Scanner

Camera

Secondary storage

Output devices display results

Monitor

Printer

Secondary storage

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

15

Software

Software are programs written to perform specific tasks

System programs control the computer

Operating system monitors the overall activity of the computer and provides services such as:

Memory management

Input/output activities

Storage management

Application programs perform a specific task

Word processors

Spreadsheets

Games

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

16

The Language of a Computer (1 of 4)

Analog signals: continuously varying continuous wave forms

Digital signals: sequences of 0s and 1s

Machine language: language of a computer

A sequence of 0s and 1s

Binary digit (bit): the digit 0 or 1

Binary code (binary number): a sequence of 0s and 1s

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

17

The Language of a Computer (2 of 4)

Byte: a sequence of eight bits

Kilobyte (KB): 210 bytes = 1024 bytes

ASCII (American Standard Code for Information Interchange)

128 characters

A is encoded as 1000001 (66th character)

The character 3 is encoded as 0110011 (51st character)

Number systems

The decimal system (base 10) is used in our daily life

The computer uses the binary (or base 2) number system

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

18

The Language of a Computer (3 of 4)

TABLE 1-1 Binary Units

Unit Symbol Bits/Bytes
Byte 8 bits
Kilobyte KB 210 bytes = 1024 bytes
Megabyte MB 1024 KB = 210 KB = 220 bytes = 1,048,576 bytes
Gigabyte GB 1024MB = 210 MB = 230 bytes = 1,073,741,824 bytes
Terabyte TB 1024 GB = 210 GB = 240 bytes = 1,099,511,627,776 bytes
Petabyte PB 1024 TB = 210 TB = 250 bytes = 1,125,899,906,842,624 bytes
Exabyte EB 1024 PB = 210 PB = 260 bytes = 1,152,921,504,606,846,976 bytes
Zettabyte ZB 1024 EB5 210 EB = 270 bytes = 1,180,591,620,717,411,303,424 bytes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

The Language of a Computer (4 of 4)

Unicode is another coding scheme

65,536 characters

Two bytes (16 bits) to store a character

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

20

The Evolution of Programming Languages (1 of 3)

Early computers were programmed in machine language

To calculate wages = rate * hours in machine language:

100100 010001 //Load

100110 010010 //Multiply

100010 010011 //Store

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

21

The Evolution of Programming Languages (2 of 3)

Assembly language instructions are mnemonic

Instructions are written in an easy-to-remember form

An assembler translates a program written in assembly language into machine language

Using assembly language instructions, wages = rate * hours can be written as:

LOAD rate

MULT hours

STOR wages

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

22

The Evolution of Programming Languages (3 of 3)

High-level languages include Basic, FORTRAN, COBOL, C, C++, C#, Java, and Python

Compiler: translates a program written in a high-level language into machine language

In C++, the weekly wages equation can be written as:

wages = rate * hours;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

23

Processing a C++ Program (1 of 4)

#include <iostream>

using namespace std;

int main()

{

cout << "My first C++ program." << endl;

return 0;

}

Sample Run:

My first C++ program.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

24

Processing a C++ Program (2 of 4)

Steps needed to process a C++ program

Use a text editor to create the source code (source program) in C++

Include preprocessor directives

Begin with the symbol # and are processed by the preprocessor

Use the compiler to:

Check that the program obeys the language rules

Translate the program into machine language (object program)

Use an integrated development environment (IDE) to develop programs in a high-level language

Programs such as mathematical functions are available

The library contains prewritten code you can use

A linker combines object program with other programs in the library to create executable code

The loader loads executable program into main memory

The last step is to execute the program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

25

Processing a C++ Program (3 of 4)

IDEs are quite user friendly

Compiler identifies the syntax errors and also suggests how to correct them

Build or Rebuild is a simple command that links the object code with the resources used from the IDE

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

26

Processing a C++ Program (4 of 4)

FIGURE 1-2 Processing a C++ program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

27

Programming with the Problem Analysis–Coding–Execution Cycle

Programming is a process of problem solving

An algorithm is a step-by-step problem-solving process

A solution is achieved in a finite amount of time

FIGURE 1-3 Problem analysis–coding–execution cycle

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

28

The Problem Analysis–Coding–Execution Cycle (1 of 5)

Step 1: Analyze the problem

Outline the problem and its requirements

Design steps (algorithm) to solve the problem

Step 2: Implement the algorithm

Implement the algorithm in code

Verify that the algorithm works

Step 3: Maintain the program

Use and modify the program if the problem domain changes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

29

The Problem Analysis–Coding–Execution Cycle (2 of 5)

Analyze the problem using these steps:

Step 1: Thoroughly understand the problem and all requirements

Step 2: Understand the problem requirements

Does program require user interaction?

Does program manipulate data?

What is the output?

Step 3: If complex, divide the problem into subproblems

Analyze and design algorithms for each subproblem

Check the correctness of algorithm

Test the algorithm using sample data

Some mathematical analysis might be required

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

30

The Problem Analysis–Coding–Execution Cycle (3 of 5)

Once the algorithm is designed and correctness is verified

Write the equivalent code in high-level language

Enter the program using a text editor

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

31

The Problem Analysis–Coding–Execution Cycle (4 of 5)

Run code through the compiler

If compiler generates errors

Look at code and remove errors

Run code again through compiler

If there are no syntax errors

Compiler generates equivalent machine code

Link machine code with the system’s resources

Performed by the linker

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

32

The Problem Analysis–Coding–Execution Cycle (5 of 5)

Once compiled and linked, the loader can place program into main memory for execution

The final step is to execute the program

Compiler guarantees that the program follows the rules of the language

Does not guarantee that the program will run correctly

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

33

Example 1-1 (1 of 2)

Design an algorithm to find the perimeter and area of a rectangle

The perimeter and area of the rectangle are given by the following formulas:

perimeter = 2 * (length + width)

area = length * width

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

34

Example 1-1 (2 of 2)

Algorithm

Get the length of the rectangle

Get the width of the rectangle

Find the perimeter with this equation:

perimeter = 2 * (length + width)

Find the area with this equation:

area = length * width

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

35

Example 1-5 (1 of 4)

Calculate each student’s grade

There are 10 students in a class

Each student has taken five tests

Each test is worth 100 points

Design algorithms to:

Calculate the grade for each student and class average

Find the average test score

Determine the grade

Use the provided data: students’ names and test scores

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

36

Example 1-5 (2 of 4)

Algorithm to determine the average test score

Get the five test scores

Add the five test scores

The sum of the test scores is represented by sum

Suppose average stands for the average test score:

average = sum / 5;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

37

Example 1-5 (3 of 4)

Algorithm to determine the grade:

if average is greater than or equal to 90

grade = A

otherwise

if average is greater than or equal to 80 and less than 90

grade = B

otherwise

if average is greater than or equal to 70 and less than 80

grade = C

otherwise

if average is greater than or equal to 60 and less than 70

grade = D

otherwise

grade = F

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

38

Example 1-5 (4 of 4)

Main algorithm is presented below:

totalAverage = 0;

Repeat the following for each student:

Get student’s name

Use the algorithm to find the average test score

Use the algorithm to find the grade

Update totalAverage by adding current student’s average test score

Determine the class average as follows: classAverage = totalAverage / 10

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

39

Programming Methodologies

Two popular approaches to programming design

Structured

Object-oriented

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

40

Structured Programming

Structured design

Involves dividing a problem into smaller subproblems

Structured programming

Involves implementing a structured design

The structured design approach is also called:

Top-down (or bottom-up) design

Stepwise refinement

Modular programming

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

41

Object-Oriented Programming (1 of 3)

Object-oriented design (OOD)

Identify components called objects

Determine how objects interact with each other

Specify relevant data and possible operations to be performed on that data

Each object consists of data and operations on that data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

42

Object-Oriented Programming (2 of 3)

An object combines data and operations on the data into a single unit

A programming language that implements OOD is called an object-oriented programming (OOP) language

To design and use objects, you must learn how to:

Represent data in computer memory

Manipulate data

Implement operations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

43

Object-Oriented Programming (3 of 3)

To create operations:

Write algorithms and implement them in a programming language

Use functions to implement algorithms

Learn how to combine data and operations on the data into a single unit called a class

C++ was designed to implement OOD

OOD is used with structured design

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

44

ANSI/ISO Standard C++

C++ evolved from C

C++ designed by Bjarne Stroustrup at Bell Laboratories in early 1980s

Many different C++ compilers were available

C++ programs were not always portable from one compiler to another

In mid-1998, ANSI/ISO C++ language standards were approved

Second standard, called C++11, was approved in 2011

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

45

Quick Review (1 of 3)

A computer is an electronic device that can perform arithmetic and logical operations

A computer system has hardware and software components

The central processing unit (CPU) is the brain

Primary storage (MM) is volatile; secondary storage (e.g., disk) is permanent

The operating system monitors overall activity of the computer and provides services

There are various kinds of languages

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

46

Quick Review (2 of 3)

Compiler: translates high-level language into machine code

Algorithm:

Step-by-step problem-solving process

Arrives at a solution in a finite amount of time

Problem-solving process

Analyze the problem and design an algorithm

Implement the algorithm in code

Maintain the program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

47

Quick Review (3 of 3)

Structured design

Problem is divided into smaller subproblems

Each subproblem is solved

Combine solutions to all subproblems

Object-oriented design (OOD) program: a collection of interacting objects

Object: data and operations on those data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

48

9781337117562_ppt_ch02.pptx

Chapter 2

Basic Elements of C++

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

Objectives (1 of 3)

In this chapter, you will:

Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers

Explore simple data types

Discover how to use arithmetic operators

Examine how a program evaluates arithmetic expressions

Become familiar with the string data type

Learn what an assignment statement is and what it does

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

2

‹#›

2

Objectives (2 of 3)

Learn about variable declaration

Discover how to input data into memory using input statements

Become familiar with the use of increment and decrement operators

Examine ways to output results using output statements

Learn how to use preprocessor directives and why they are necessary

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

3

‹#›

Objectives (3 of 3)

Learn how to debug syntax errors

Explore how to properly structure a program, including using comments to document a program

Become familiar with compound statements

Learn how to write a C++ program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

4

‹#›

Introduction

Computer program

A sequence of statements whose objective is to accomplish a task

Programming

The process of planning and creating a program

Real-world analogy: a recipe for cooking

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

5

‹#›

5

A Quick Look at a C++ Program (1 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

6

‹#›

6

A Quick Look at a C++ Program (2 of 5)

Sample Run:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

7

‹#›

7

A Quick Look at a C++ Program (3 of 5)

FIGURE 2-1 Various parts of a C++ program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

8

‹#›

8

A Quick Look at a C++ Program (4 of 5)

FIGURE 2-1 Various parts of a C++ program (cont’d.)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

9

‹#›

9

A Quick Look at a C++ Program (5 of 5)

Variable: a memory location whose contents can be changed

FIGURE 2-3 Memory allocation

FIGURE 2-4 Memory spaces after the statement length = 6.0; executes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

10

‹#›

10

The Basics of a C++ Program

Subprogram (or function): collection of statements

When executed, accomplishes something

May be predefined or standard

Syntax rules: rules that specify which statements (instructions) are legal or valid

Semantic rules: determine the meaning of the instructions

Programming language: a set of rules, symbols, and special words

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

11

‹#›

11

Comments

Comments are for the reader, not the compiler

Two types

Single line: begins with //

//**************************************************************

// Given the length and width of a rectangle, this C++ program

// computes and outputs the perimeter and area of the rectangle.

//**************************************************************

Multiple line: enclosed between /* and */

/*

You can include comments that can

occupy several lines.

*/

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

12

‹#›

12

Special Symbols

A token is the smallest individual unit of a program written in any language

C++ tokens include special symbols, word symbols, and identifiers

Special symbols in C++ include:

+ - * /

. ; ? ,

<= != == >=

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

13

‹#›

13

Reserved Words (Keywords)

Reserved word symbols (or keywords):

Cannot be redefined within a program

Cannot be used for anything other than their intended use

Examples include:

int

float

double

char

const

void

return

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

14

‹#›

14

Identifiers (1 of 2)

An identifier is the name of something that appears in a program

Consists of letters, digits, and the underscore character (_)

Must begin with a letter or underscore

C++ is case sensitive

NUMBER is not the same as number

Two predefined identifiers are cout and cin

Unlike reserved words, predefined identifiers may be redefined, but it is not a good idea

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

15

‹#›

15

Identifiers (2 of 2)

Legal identifiers in C++

first

conversion

payRate

TABLE 2-1 Examples of Illegal Identifiers

Illegal Identifier Reason A Correct Identifier
employee Salary There can be no space between employee and Salary. employeeSalary
Hello! The exclamation mark cannot be used in an identifier. Hello
one+two The symbol + cannot be used in an identifier. onePlusTwo
2nd An identifier cannot begin with a digit. second

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

16

‹#›

16

Whitespaces

Every C++ program contains whitespaces

Include blanks, tabs, and newline characters

Whitespaces separate special symbols, reserved words, and identifiers

Proper utilization of whitespaces is important

Can be used to make the program more readable

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

17

‹#›

17

Data Types

A data type is set of values together with a set of allowed operations

C++ data types fall into three categories:

Simple data type

Structured data type

Pointers

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

18

‹#›

18

Simple Data Types (1 of 2)

Three categories of simple data

Integral: integers (numbers without a decimal)

Can be further categorized: char, short, int, long, bool, unsigned char, unsigned short, unsigned int, unsigned long

Floating-point: decimal numbers

Enumeration: a user-defined data type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

19

‹#›

19

Simple Data Types (2 of 2)

Different compilers may allow different ranges of values

TABLE 2-2 Values and Memory Allocation for Simple Data Types

Data Type Values Storage (in bytes)
int –147483648 (= –231 ) to 2147483647 (= 231 – 1) 4
bool true and false 1
char –128 (= –27 ) to 127 (= 27 – 1) 1
long long –9223372036854775808 (–263 ) to 9223372036854775807(263 – 1) 64

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

20

‹#›

20

int Data Type

Examples

-6728

0

78

+763

Positive integers do not require a + sign

A comma cannot be used within an integer

Commas are only used for separating items in a list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

21

‹#›

21

bool Data Type

bool type

Two values: true and false

Purpose: to manipulate logical (Boolean) expressions

true and false

Logical values

bool, true, and false

Reserved words

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

22

‹#›

22

char Data Type (1 of 2)

Data type char is the smallest integral data type

It is used for single characters: letters, digits, and special symbols

Each character is enclosed in single quotes

'A', 'a', '0', '*', '+', '$', '&'

A blank space is a character

Written ' ', with a space left between the single quotes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

23

‹#›

23

char Data Type (2 of 2)

Different character data sets exist

ASCII: American Standard Code for Information Interchange

Each of 128 values in ASCII code set represents a different character

Characters have a predefined ordering based on the ASCII numeric value

Collating sequence: ordering of characters based on the character set code

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

24

‹#›

24

Floating-Point Data Types (1 of 3)

C++ uses scientific notation to represent real numbers (floating-point notation)

TABLE 2-3 Examples of Decimal Numbers in Scientific and C11 Floating-Point Notations

Decimal Number Scientific Notation C++ Floating-Point Notation
75.924 7.5924 * 101 7.592400E1
0.18 1.8 * 10-1 1.800000E-1
0.0000453 4.53 * 10-5 4.530000E-5
–1.482 -1.482 * 100 -1.482000E0
7800.0 7.8 * 103 7.800000E3

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

25

‹#›

25

Floating-Point Data Types (2 of 3)

float: represents any real number

Range: -3.4 * 1038 to 3.4 * 1038 (four bytes)

double: represents any real number

Range: –1.7 * 10308 to 1.7 * 10308 (eight bytes)

Minimum and maximum values of data types are system dependent

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

26

‹#›

26

Floating-Point Data Types (3 of 3)

Maximum number of significant digits (decimal places) for float values: 6 or 7

Maximum number of significant digits for double: 15

Precision: maximum number of significant digits

float values are called single precision

double values are called double precision

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

27

‹#›

27

Data Types, Variables, and Assignment Statements

To declare a variable, must specify its data type

Syntax rule to declare a variable is:

dataType identifier;

Examples include:

int counter;

double interestRate;

char grade;

Assignment statement has the form: variable = expression

Example: interestRate = 0.05;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

28

‹#›

28

Arithmetic Operators, Operator Precedence, and Expressions (1 of 2)

C++ arithmetic operators include:

+ addition

- subtraction (or negation)

* multiplication

/ division

% mod (modulus or remainder)

+, -, *, and / can be used with integral and floating-point data types

Modulus (%) can only be used with integral data types

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

29

‹#›

29

Arithmetic Operators, Operator Precedence, and Expressions (2 of 2)

When you use / with integral data types, the integral result is truncated (no rounding)

Arithmetic expressions contain values and arithmetic operators

Operands are the numbers appearing in the expressions

Operators can be unary (one operand) or binary (two operands)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

30

‹#›

30

Order of Precedence

All operations inside () are evaluated first

*, /, and % are at the same level of precedence and are evaluated next

+ and - have the same level of precedence and are evaluated last

When operators are on the same level

Operations are performed from left to right (associativity)

3 * 7 - 6 + 2 * 5 / 4 + 6 means (((3 * 7) – 6) + ((2 * 5) / 4 )) + 6

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

31

‹#›

31

Expressions

Integral expression: all operands are integers

Yields an integral result

Example: 2 + 3 * 5

Floating-point (decimal) expression: all operands are floating-point

Yields a floating-point result

Example: 12.8 * 17.5 - 34.50

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

32

‹#›

32

Mixed Expressions (1 of 2)

Mixed expression

Has operands of different data types

Contains integers and floating-point

Examples of mixed expressions

2 + 3.5

6 / 4 + 3.9

5.4 * 2 – 13.6 + 18 / 2

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

33

‹#›

33

Mixed Expressions (2 of 2)

Evaluation rules

If operator has same types of operands

The operator is evaluated according to the type of the operands

If operator has both types of operands

Integer is changed to floating-point

Operator is evaluated

Result is floating-point

Entire expression is evaluated according to precedence rules

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

34

‹#›

34

Type Conversion (Casting) (1 of 2)

Implicit type coercion: when the value of one type is automatically changed to another type

Cast operator (also called type conversion or type casting): provides explicit type conversion

static_cast<dataTypeName>(expression)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

35

‹#›

35

Type Conversion (Casting) (2 of 2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

36

‹#›

36

string Type

Data type string is a programmer-defined type supplied in ANSI/ISO Standard C++ library

A string is a sequence of zero or more characters enclosed in double quotation marks

A null (or empty) string is a string with no characters

Each character has a relative position in the string

Position of first character is 0

The length of a string is the number of characters in it

Example: length of "William Jacob" is 13

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

37

‹#›

37

Variables, Assignment Statements, and Input Statements

Data must be loaded into main memory before it can be manipulated

Storing data in memory is a two-step process:

Instruct the computer to allocate memory

Include statements in the program to put data into the allocated memory

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

38

‹#›

38

Allocating Memory with Constants and Variables (1 of2)

Named constant: memory location whose content cannot change during execution

Syntax to declare a named constant

In C++, const is a reserved word

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

39

‹#›

39

Allocating Memory with Constants and Variables (2 of 2)

Variable: memory location whose content may change during execution

Syntax to declare one or multiple variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

40

‹#›

40

Putting Data into Variables

Ways to place data into a variable

Use C++’s assignment statement

Use input (read) statements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

41

‹#›

41

Assignment Statement (1 of 4)

The assignment statement takes the form:

Expression is evaluated and its value is assigned to the variable on the left side

A variable is said to be initialized the first time a value is placed into it

In C++, = is called the assignment operator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

42

‹#›

42

Assignment Statement (2 of 4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

43

‹#›

43

Assignment Statement (3 of 4)

Example 2-14 illustrates a walk-through (tracing values through a sequence)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

44

‹#›

44

Assignment Statement (4 of 4)

Given int variables x, y, and z. How is this legal C++ statement evaluated?

x = y = z

The assignment operator is evaluated from right to left

The associativity of the assignment operator is from right to left

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

45

‹#›

45

Saving and Using the Value of an Expression

Declare a variable of the appropriate data type

Assign the value of the expression to the variable that was declared

Use the assignment statement

Wherever the value of the expression is needed, use the variable holding the value

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

46

‹#›

46

Declaring and Initializing Variables

Not all types of variables are initialized automatically

Variables can be initialized when declared:

int first = 13, second = 10;

char ch = ' ';

double x = 12.6;

All variables must be initialized before they are used

But not necessarily during declaration

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

47

‹#›

47

Input (Read) Statement (1 of 3)

cin is used with >> to gather one or more inputs

This is called an input (read) statement

The stream extraction operator is >>

For example, if miles is a double variable: cin >> miles;

Causes the computer to get a value of type double and places it in the variable miles

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

48

‹#›

48

Input (Read) Statement (2 of 3)

Using more than one variable in cin allows more than one value to be read at a time

Example: if feet and inches are variables of type int, this statement:

cin >> feet >> inches;

Inputs two integers from the keyboard

Places them in variables feet and inches respectively

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

49

‹#›

49

Input (Read) Statement (3 of 3)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

50

‹#›

50

Increment and Decrement Operators

Increment operator (++): increase variable by 1

Pre-increment: ++variable

Post-increment: variable++

Decrement operator: (--) decrease variable by 1

Pre-decrement: --variable

Post-decrement: variable--

What is the difference between the following?

x = 5;

y = ++x;

x = 5;

y = x++;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

51

‹#›

51

Output (1 of 4)

The syntax of cout and << is:

Called an output statement

The stream insertion operator is <<

Expression evaluated and its value is printed at the current cursor position on the screen

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

52

‹#›

52

Output (2 of 4)

A manipulator is used to format the output

Example: endl causes the insertion point to move to beginning of next line

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

53

‹#›

53

Output (3 of 4)

The new line character (new line escape sequence) is '\n'

May appear anywhere in the string

Examples

cout << "Hello there.";

cout << "My name is James.";

Output:

Hello there.My name is James.

cout << "Hello there.\n";

cout << "My name is James.";

Output :

Hello there.

My name is James.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

54

‹#›

54

Output (4 of 4)

TABLE 2-4 Commonly Used Escape Sequences

Escape Sequence Description
\n Newline Cursor moves to the beginning of the next line
\t Tab Cursor moves to the next tab stop
\b Backspace Cursor moves one space to the left
\r Return Cursor moves to the beginning of the current line (not the next line)
\\ Backslash Backslash is printed
\' Single quotation Single quotation mark is printed
\" Double quotation Double quotation mark is printed

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

55

‹#›

55

Preprocessor Directives (1 of 2)

C++ has a small number of operations

Many functions and symbols needed to run a C++ program are provided as collection of libraries

Every library has a name and is referred to by a header file

Preprocessor directives are processed by the preprocessor program

All preprocessor commands begin with #

No semicolon is placed at the end of these commands

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

56

‹#›

56

Preprocessor Directives (2 of 2)

Syntax to include a header file

For example:

#include <iostream>

Causes the preprocessor to include the header file iostream in the program

Preprocessor commands are processed before the program goes through the compiler

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

57

‹#›

57

namespace and Using cin and cout in a Program

cin and cout are declared in the header file iostream, but within std namespace

To use cin and cout in a program, use the following two statements:

#include <iostream>

using namespace std;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

58

‹#›

58

Using the string Data Type in a Program

To use the string type, you need to access its definition from the header file string

Include the following preprocessor directive:

#include <string>

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

59

‹#›

59

Creating a C++ Program (1 of 3)

A C++ program is a collection of functions, one of which is the function main

The syntax of the function main used in this book has this form:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

60

‹#›

60

Creating a C++ Program (2 of 3)

Source code is comprised of preprocessor directives and program statements

The source code file (source file) contains the source code

The compiler generates the object code (file extension .obj)

Executable code (file extension .exe) results when object code is linked with the system resources

The first line of the function main is called the heading of the function:

int main()

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

61

‹#›

61

Creating a C++ Program (3 of 3)

The statements enclosed between the curly braces ({ and }) form the body of the function

A C++ program contains two types of statements:

Declaration statements declare things, such as variables

Executable statements perform calculations, manipulate data, create output, accept input, etc.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

62

‹#›

62

Debugging: Understanding and Fixing Syntax Errors (1 of 2)

Sample program with line numbers added on the left

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

63

‹#›

63

Debugging: Understanding and Fixing Syntax Errors (2 of 2)

Compile the program

Compiler will identify the syntax errors

The line numbers where the errors occur are specified:

ExampleCh2_Syntax_Errors.cpp

c:\examplech2_syntax_errors.cpp(9): error C2146: syntax error:

missing ';' before identifier 'num'

c:\examplech2_syntax_errors.cpp(11): error C2065: 'tempNum':

undeclared identifier

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

64

‹#›

64

Program Style and Form: Syntax

Syntax rules indicate what is legal and what is not legal

Errors in syntax are found in compilation

int x; //Line 1

int y //Line 2

double z; //Line 3

y = w + x; //Line 4

Compilation errors would occur at:

Line 2 (missing semicolon)

Line 4 (identifier w used but not declared)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

65

‹#›

65

Use of Blanks

In C++, you use one or more blanks to separate numbers when data is input

Blanks are also used to separate reserved words and identifiers from each other and from other symbols

Blanks must never appear within a reserved word or identifier

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

66

‹#›

66

Use of Semicolons, Brackets, and Commas

All C++ statements end with a semicolon

Also called a statement terminator

{ and } are not C++ statements

Can be regarded as delimiters

Commas separate items in a list

Declaring more than one variable following a data type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

67

‹#›

67

Semantics

Semantics: set of rules that gives meaning to a language

Possible to remove all syntax errors in a program and still not have it run

Even if it runs, it may still not do what you meant it to do

Example: 2 + 3 * 5 and (2 + 3) * 5

Both are syntactically correct expressions but have different meanings

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

68

‹#›

68

Naming Identifiers

Identifiers can be self-documenting

CENTIMETERS_PER_INCH

Avoid run-together words

annualsale

Solutions may include:

Capitalizing the beginning of each new word: annualSale

Inserting an underscore just before a new word: annual_sale

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

69

‹#›

69

Prompt Lines

Prompt lines: executable statements that inform the user what to do

cout << "Please enter a number between 1 and 10 and "

<< "press the return key" << endl;

cin >> num;

Always include prompt lines when input is needed from users

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

70

‹#›

70

Documentation

A well-documented program is easier to understand and modify

You use comments to document programs

Comments should appear in a program to:

Explain the purpose of the program

Identify who wrote it

Explain the purpose of particular statements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

71

‹#›

71

Form and Style

Consider two ways of declaring variables:

Method 1

int feet, inches;

double x, y;

Method 2

int feet,inches; double x,y;

Both are correct; however, the second is harder to read

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

72

‹#›

72

More on Assignment Statements

Two forms of assignment

Simple and compound

Compound operators provide more concise notation

Compound operators: +=, -=, *=, /=, %=

Simple assignment statement example

x = x * y;

Compound assignment statement example

x *= y;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

73

‹#›

73

Quick Review (1 of 3)

A C++ program is a collection of functions, one of which is always called main

Identifiers consist of letters, digits, and underscores, and begin with a letter or an underscore

The arithmetic operators in C++ are addition (+), subtraction (-), multiplication (*), division (/), and modulus (%)

Arithmetic expressions are evaluated using the precedence associativity rules

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

74

‹#›

74

Quick Review (2 of 3)

All operands in an integral expression are integers

All operands in a floating-point expression are decimal numbers

A mixed expression contains both integers and decimal numbers

Use the cast operator to explicitly convert values from one data type to another

A named constant is initialized when declared

All variables must be declared before used

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

75

‹#›

75

Quick Review (3 of 3)

Use cin and the stream extraction operator >> to input from the standard input device

Use cout and the stream insertion operator << to output to the standard output device

Preprocessor commands are processed before the program goes through the compiler

A file containing a C++ program usually ends with the extension .cpp

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

76

‹#›

76

9781337117562_ppt_ch03.pptx

Chapter 3

Input/Output

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn what a stream is and examine input and output streams

Explore how to read data from the standard input device

Learn how to use predefined functions in a program

Explore how to use the input stream functions get, ignore, putback, and peek

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

2

‹#›

2

Objectives (2 of 2)

Become familiar with input failure

Learn how to write data to the standard output device

Discover how to use manipulators in a program to format output

Learn how to perform input and output operations with the string data type

Learn how to debug logic errors

Become familiar with file input and output

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

3

‹#›

3

I/O Streams and Standard I/O Devices (1 of 3)

I/O: sequence of bytes (stream of bytes) from source to destination

Bytes are usually characters, unless program requires other types of information

Stream: sequence of characters from the source to the destination

Input stream: sequence of characters from an input device to the computer

Output stream: sequence of characters from the computer to an output device

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

4

‹#›

4

I/O Streams and Standard I/O Devices (2 of 3)

Use iostream header file to receive data from keyboard and send output to the screen

Contains definitions of two data types:

istream: input stream

ostream: output stream

Has two variables:

cin: stands for common input

cout: stands for common output

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

5

‹#›

5

I/O Streams and Standard I/O Devices (3 of 3)

Variable declaration is similar to:

istream cin;

ostream cout;

To use cin and cout, the preprocessor directive #include <iostream> must be used

Input stream variables: type istream

Output stream variables: type ostream

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

6

‹#›

6

cin and the Extraction Operator >> (1 of 7)

The syntax of an input statement using cin and the extraction operator >> is

The extraction operator >> is binary

Left-side operand is an input stream variable

Example: cin

Right-side operand is a variable

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

7

‹#›

7

cin and the Extraction Operator >> (2 of 7)

No difference between a single cin with multiple variables and multiple cin statements with one variable in each statement

cin >> payRate >> hoursWorked; cin >> payRate; cin >> hoursWorked;

When scanning, >> skips all whitespace

Blanks and certain nonprintable characters

>> distinguishes between character 2 and number 2 by the right-side operand of >>

If type char or int (or double), the 2 is treated as a character or as a number 2, respectively

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

8

‹#›

8

cin and the Extraction Operator >> (3 of 7)

TABLE 3-1 Valid Input for a Variable of the Simple Data Type

Data Type of a Valid Input for a
char One printable character except the blank.
int An integer, possibly preceded by a + or - sign.
double A decimal number, possibly preceded by a + or - sign. If the actual data input is an integer, the input is converted to a decimal number with the zero decimal part.

Entering a char value into an int or double variable causes serious errors, called input failure

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

9

‹#›

9

cin and the Extraction Operator >> (4 of 7)

When reading data into a char variable

>> skips leading whitespace, finds and stores only the next character

Reading stops after a single character

To read data into an int or double variable

>> skips leading whitespace, reads + or - sign (if any), reads the digits (including decimal for floating-point variables)

Reading stops on whitespace or a non-digit character

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

10

‹#›

10

cin and the Extraction Operator >> (5 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

11

‹#›

11

cin and the Extraction Operator >> (6 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

12

‹#›

12

cin and the Extraction Operator >> (7 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

13

‹#›

13

Using Predefined Functions in a Program (1 of 3)

A function (subprogram) is a set of instructions

When activated, it accomplishes a task

main executes when a program is run

Other functions execute only when called

C++ includes a wealth of functions

Predefined functions are organized as a collection of libraries called header files

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

14

‹#›

14

Using Predefined Functions in a Program (2 of 3)

Header file may contain several functions

To use a predefined function, you need the name of the appropriate header file

You also need to know:

Function name

Number of parameters required

Type of each parameter

What the function is going to do

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

15

‹#›

15

Using Predefined Functions in a Program (3 of 3)

To use pow (power), include cmath

Two numeric parameters

Syntax: pow(x,y) = xy

x and y are the arguments or parameters

In pow(2,3), the parameters are 2 and 3

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

16

‹#›

16

cin and the get Function

The get function

Inputs next character (including whitespace)

Stores in memory location indicated by its argument

The syntax of cin and the get function

varChar is a char variable

It is the argument (or parameter) of the function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

17

‹#›

17

cin and the ignore Function (1 of 2)

ignore function

Discards a portion of the input

The syntax to use the function ignore is:

intExp is an integer expression

chExp is a char expression

If intExp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chExp

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

18

‹#›

18

cin and the ignore Function (2 of 2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

19

‹#›

19

The putback and peek Functions (1 of 2)

putback function

Places previous character extracted by the get function from an input stream back to that stream

peek function

Returns next character from the input stream

Does not remove the character from that stream

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

20

‹#›

20

The putback and peek Functions (2 of 2)

Syntax for putback

istreamVar: an input stream variable (such as cin)

ch is a char variable

Syntax for peek

istreamVar: an input stream variable (such as cin)

ch is a char variable

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

21

‹#›

21

The Dot Notation between I/O Stream Variables and I/O Functions: A Precaution

In the statement

cin.get(ch);

cin and get are two separate identifiers separated by a dot

Called the dot notation, the dot separates the input stream variable name from the member, or function, name

In C++, the dot is the member access operator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

22

‹#›

22

Input Failure

Things can go wrong during execution

If input data does not match corresponding variables, the program may run into problems

Trying to read a letter into an int or double variable will result in an input failure

If an error occurs when reading data

Input stream enters the fail state

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

23

‹#›

23

The clear Function

Once in a fail state, all further I/O statements using that stream are ignored

The program continues to execute with whatever values are stored in variables

This causes incorrect results

The clear function restores the input stream to a working state

The syntax of the function clear is:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

24

‹#›

24

Output and Formatting Output

Syntax of cout when used with <<

expression is evaluated

value is printed

manipulator is used to format the output

Example: endl

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

25

‹#›

25

setprecision Manipulator

Syntax

Outputs decimal numbers with up to n decimal places

Must include the header file iomanip

#include <iomanip>

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

26

‹#›

26

fixed Manipulator

fixed outputs floating-point numbers in a fixed decimal format

Example: cout << fixed;

Disable by using the stream member function unsetf

Example: cout.unsetf(ios::fixed);

scientific manipulator outputs floating-point numbers in scientific format

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

27

‹#›

27

showpoint Manipulator

showpoint forces output to show the decimal point and trailing zeros

Examples

cout << showpoint;

cout << fixed << showpoint;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

28

‹#›

28

C++14 Digit Separator

Reading and writing of long numbers can be error prone

In C++, commas cannot be used to separate the digits of a number

C++14 introduces digit separator ' (single-quote character)

Example: 87523872918 can be represented as 87'523'872'918

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

29

‹#›

29

setw

Outputs the value of an expression in a specified number of columns

cout << setw(5) << x << endl;

If number of columns exceeds the number of columns required by the expression

Output of the expression is right-justified

Unused columns to the left are filled with spaces

Must include the header file iomanip

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

30

‹#›

30

Additional Output Formatting Tools

Additional formatting tools that give you more control over your output:

setfill manipulator

left and right manipulators

unsetf manipulator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

31

‹#›

31

setfill Manipulator

Output stream variables can use setfill to fill unused columns with a character

Example:

cout << setfill('#');

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

32

‹#›

32

left and right Manipulators

left manipulator left-justifies the output

Disable left by using unsetf

right manipulator right-justifies the output

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

33

‹#›

33

Types of Manipulators

Two types of manipulators

Those with parameters

Those without parameters

Parameterized stream manipulators require the iomanip header

setprecision, setw, and setfill

Manipulators without parameters require the iostream header

endl, fixed, scientific, showpoint, and left

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

34

‹#›

34

Input/Output and the string Type

An input stream variable (such as cin) and >> operator can read a string into a variable of the data type string

The extraction operator:

Skips any leading whitespace characters

Stops reading at a whitespace character

The function getline reads until end of the current line

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

35

‹#›

35

Debugging: Understanding Logic Errors and Debugging with cout statements

Syntax errors are reported by the compiler

Logic errors are typically not caught by the compiler

Spot and correct using cout statements

Temporarily insert an output statement

Correct the problem

Remove output statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

36

‹#›

36

File Input/Output

A file is an area in secondary storage to hold info

File I/O is a five-step process

Include fstream header

Declare file stream variables

Associate the file stream variables with the input/output sources – referred to as opening the files

Use the file stream variables with >>, <<, or other input/output functions

Close the files

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

37

‹#›

37

Quick Review (1 of 3)

Stream: infinite sequence of characters from a source to a destination

Input stream: from a source to a computer

Output stream: from a computer to a destination

cin: common input

cout: common output

To use cin and cout, include iostream header

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

38

‹#›

38

Quick Review (2 of 3)

get reads data character-by-character

ignore skips data in a line

putback puts last character retrieved by get back to the input stream

peek returns next character from input stream, but does not remove it

Attempting to read invalid data into a variable causes the input stream to enter the fail state

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

39

‹#›

39

Quick Review (3 of 3)

The manipulators setprecision, fixed, showpoint, setw, setfill, left, and right can be used for formatting output

Include iomanip for the manipulators setprecision, setw, and setfill

Header fstream contains the definitions of ifstream and ofstream

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

40

‹#›

40

9781337117562_ppt_ch04.pptx

Chapter 4

Control Structures I (Selection)

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn about control structures

Examine relational operators

Discover how to use the selection control structures if, if…else

Examine int and bool data types and logical (Boolean) expressions

Examine logical operators

Explore how to form and evaluate logical (Boolean) expressions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Learn how relational operators work with the string type

Become aware of short-circuit evaluation

Learn how the conditional operator, ?:, works

Learn how to use pseudocode to develop, test, and debug a program

Discover how to use a switch statement in a program

Learn how to avoid bugs by avoiding partially understood concepts

Learn how to use the assert function to terminate a program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Control Structures (1 of 2)

A computer can proceed:

In sequence

Selectively (branch): making a choice

Repetitively: looping

By calling a function

The two most common control structures are:

Selection

Repetition

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Control Structures (2 of 2)

FIGURE 4-1 Flow of execution

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Selection: if and if...else

An expression that evaluates to true or false is called a logical expression

“8 is greater than 3” is true

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Relational Operators

TABLE 4-1 Relational Operators in C++

Operator Description
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to

Each relational operator is a binary operator (requires two operands)

Expressions using these operators always evaluate to true or false

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Relational Operators and Simple Data Types

You can use the relational operators with all three simple data types

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Comparing Characters

In an expression of char values using relational operators:

The result depends on the machine’s collating sequence

ASCII character set

Logical (Boolean) expressions:

Include expressions such as 4 < 6 and 'R' > 'T’

Return an integer value of 1 if the logical expression evaluates to true

Return an integer value of 0 otherwise

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

One-Way Selection (1 of 2)

One-way selection syntax

The statement is:

Executed if the value of the expression is true

Bypassed if the value is false; program goes to the next statement

The expression is also called a decision maker

The statement following the expression is also called the action statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

One-Way Selection (2 of 2)

FIGURE 4-2 One-way selection

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Two-Way Selection (1 of 2)

Two-way selection syntax

If expression is true, statement1 is executed; otherwise, statement2 is executed

statement1 and statement2 are any C++ statements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Two-Way Selection (2 of 2)

FIGURE 4-3 Two-way selection

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

int Data Type and Logical (Boolean) Expressions

Earlier versions of C++ did not provide built-in data types that had Boolean values

Logical expressions evaluate to either 1 or 0

Logical expression value was stored in a variable of the data type int

You can use the int data type to manipulate logical (Boolean) expressions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

bool Data Type and Logical (Boolean) Expressions

The data type bool has logical (Boolean) values true and false

bool, true, and false are reserved words

The identifier true has the value 1

The identifier false has the value 0

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Logical (Boolean) Operators and Logical Expressions (1 of 5)

Logical (Boolean) operators enable you to combine logical expressions

TABLE 4-2 Logical (Boolean) Operators in C++

Operator Description
! not
&& and
|| or

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Logical (Boolean) Operators and Logical Expressions (2 of 5)

TABLE 4-3 The ! (Not) Operator

Expression !(Expression)
true (nonzero) false (0)
false (0) true (1)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Logical (Boolean) Operators and Logical Expressions (3 of 5)

TABLE 4-4 The && (And) Operator

Expression1 Expression2 Expression1 && Expression2
true (nonzero) true (nonzero) true (1)
true (nonzero) false (0) false (0)
false (0) true (nonzero) false (0)
false (0) false (0) false (0)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Logical (Boolean) Operators and Logical Expressions (4 of 5)

TABLE 4-5 The || (Or) Operator

Expression1 Expression2 Expression1 || Expression2
true (nonzero) true (nonzero) true (1)
true (nonzero) false (0) true (1)
false (0) true (nonzero) true (1)
false (0) false (0) false (0)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Logical (Boolean) Operators and Logical Expressions (5 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Order of Precedence (1 of 5)

Relational and logical operators are evaluated from left to right

The associativity is left to right

Parentheses can override precedence

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Order of Precedence (2 of 5)

TABLE 4-6 Precedence of Operators

Operators Precedence
!, +, - (unary operators) first
*, /, % second
+, - third
<, <=, >=, > fourth
==, != fifth
&& sixth
|| seventh
= (assignment operator) last

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Order of Precedence (3 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Order of Precedence (4 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Order of Precedence (5 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Relational Operators and the string Type (1 of 5)

Relational operators can be applied to variables of type string

Strings are compared character by character, starting with the first character

Comparison continues until either a mismatch is found or all characters are found equal

If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string

The shorter string is less than the larger string

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Relational Operators and the string Type (2 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

Relational Operators and the string Type (3 of 5)

Expression Value/Explanation
str1 < str2 true str1 = "Hello" and str2 = "Hi". The first character of str1 and str2 are the same, but the second character 'e' of str1 is less than the second character 'i' of str2. Therefore, str1 < str2 is true.
str1 > "Hen" false str1 = "Hello". The first two characters of str1 and "Hen" are the same, but the third character 'l' of str1 is less than the third character 'n' of "Hen". Therefore, str1 > "Hen" is false.
str3 < "An" true str3 = "Air". The first characters of str3 and "An" are the same, but the second character 'i' of "Air" is less than the second character 'n' of "An". Therefore, str3 < "An" is true.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Relational Operators and the string Type (4 of 5)

Expression Value/Explanation
str1 == "hello" false str1 = "Hello". The first character 'H' of str1 is less than the first character 'h' of "hello" because the ASCII value of 'H' is 72, and the ASCII value of 'h' is 104. Therefore, str1 == "hello" is false.
str3 <= str4 true str3 = "Air" and str4 = "Bill". The first character 'A' of str3 is less than the first character 'B' of str4. Therefore, str3 <= str4 is true.
str2 > str4 true str2 = "Hi" and str4 = "Bill". The first character 'H' of str2 is greater than the first character 'B' of str4. Therefore, str2 > str4 is true.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Relational Operators and the string Type (5 of 5)

Expression Value/Explanation
str4 >= "Billy" false str4 = "Bill". It has four characters and "Billy" has five characters. Therefore, str4 is the shorter string. All four characters of str4 are the same as the corresponding first four characters of "Billy", and "Billy" is the larger string. Therefore, str4 >= "Billy" is false.
str5 <= "Bigger" true str5 = "Big". It has three characters and "Bigger" has six characters. Therefore, str5 is the shorter string. All three characters of str5 are the same as the corresponding first three characters of "Bigger", and "Bigger" is the larger string. Therefore, str5 <= "Bigger" is true.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Compound (Block of) Statements (1 of 2)

A compound statement (block of statements) has this form:

A compound statement functions like a single statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

Compound (Block of) Statements (2 of 2)

if (age > 18)

{

cout << "Eligible to vote." << endl;

cout << "No longer a minor." << endl;

}

else

{

cout << "Not eligible to vote." << endl;

cout << "Still a minor." << endl;

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

Multiple Selections: Nested if (1 of 2)

When one control statement is located within another, it is said to be nested

An else is associated with the most recent if that has not been paired with an else

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

Multiple Selections: Nested if (2 of 2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

Comparing if…else Statements with a Series of if Statements (1 of 2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

Comparing if…else Statements with a Series of if Statements (2 of 2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Short-Circuit Evaluation

Short-circuit evaluation: evaluation of a logical expression stops as soon as the value of the expression is known

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Comparing Floating-Point Numbers for Equality: A Precaution

Comparison of floating-point numbers for equality may not behave as you would expect

Example:

1.0 == 3.0/7.0 + 2.0/7.0 + 2.0/7.0 evaluates to false

Why? 3.0/7.0 + 2.0/7.0 + 2.0/7.0 = 0.99999999999999989

A solution is checking for a tolerance value

Example: if fabs(x – y) < 0.000001

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Associativity of Relational Operators: A Precaution (1 of 2)

#include <iostream>

using namespace std;

int main()

{

int num;

cout << "Enter an integer: ";

cin >> num;

cout << endl;

if (0 <= num <= 10)

cout << num << " is within 0 and 10." << endl;

else

cout << num << " is not within 0 and 10." <<

endl;

return 0;

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

39

Associativity of Relational Operators: A Precaution (2 of 2)

num = 5

0 <= num <= 10 = 0 <= 5 <= 10
= (0 <= 5) <= 10 (Because relational operators are evaluated from left to right)
= 1 <= 10 (Because 0 <= 5 is true, 0 <= 5 evaluates to 1)
= 1 (true)

num = 20

0 <= num <= 10 = 0 <= 20 <= 10
= (0 <= 20) <= 10 (Because relational operators are evaluated from left to right)
= 1 <= 10 (Because 0 <= 20 is true, 0 <= 20 evaluates to 1)
= 1 (true)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Avoiding Bugs by Avoiding Partially Understood Concepts and Techniques

Must use concepts and techniques correctly

Otherwise solution will be either incorrect or deficient

If you do not understand a concept or technique completely

Do not use it

Save yourself an enormous amount of debugging time

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

Input Failure and the if Statement

If an input stream enters a fail state:

All subsequent input statements associated with that stream are ignored

Program continues to execute

The code may produce erroneous results

Use if statements to check status of input stream

If the input stream enters the fail state, include instructions that stop program execution

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

42

Confusion Between the Equality (==) and Assignment (=) Operators

C++ allows you to use any expression that can be evaluated to either true or false as an expression in the if statement

if (x = 5)

cout << "The value is five." << endl;

The appearance of = in place of == resembles a silent killer

It is not a syntax error

It is a logical error

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

43

Conditional Operator (?:)

Conditional operator (?:)

Ternary operator: takes three arguments

Syntax for the conditional operator

If expression1 is true, the result of the conditional expression is expression2

Otherwise, the result is expression3

Example: max = (a >= b) ? a : b;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

44

Program Style and Form (Revisited): Indentation

A properly indented program:

Helps you spot and fix errors quickly

Shows the natural grouping of statements

Insert a blank line between statements that are naturally separate

Two commonly used styles for placing braces

On a line by themselves

Or left brace is placed after the expression, and the right brace is on a line by itself

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

45

Using Pseudocode to Develop, Test, and Debug a Program

Pseudocode (or just pseudo) is an informal mixture of C++ and ordinary language

Helps you quickly develop the correct structure of the program and avoid making common errors

Use a wide range of values in a walk-through to evaluate the program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

46

switch Structures (1 of 4)

switch structure is an alternate to if-else

switch (integral) expression is evaluated first

Value of the expression determines which corresponding action is taken

Expression is sometimes called the selector

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

47

switch Structures (2 of 4)

FIGURE 4-4 switch statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

48

switch Structures (3 of 4)

One or more statements may follow a case label

Braces are not needed to turn multiple statements into a single compound statement

When a case value is matched, all statements after it execute until a break is encountered

The break statement may or may not appear after each statement

switch, case, break, and default are reserved words

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

49

switch Structures (4 of 4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

50

Avoiding Bugs: Revisited

To output results correctly

Consider whether the switch structure must include a break statement after each cout statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

51

Terminating a Program with the assert Function

Certain types of errors are very difficult to catch

Example: division by zero

The assert function is useful in stopping program execution when certain elusive errors occur

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

52

The assert Function (1 of 2)

Syntax

expression is any logical expression

If expression evaluates to true, the next statement executes

If expression evaluates to false, the program terminates and indicates where in the program the error occurred

To use assert, include cassert header file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

53

The assert Function (2 of 2)

assert is useful for enforcing programming constraints during program development

After developing and testing a program, remove or disable assert statements

The preprocessor directive #define NDEBUG must be placed before the directive #include <cassert> to disable the assert statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

54

Quick Review (1 of 3)

Control structures alter normal control flow

Most common control structures are selection and repetition

Relational operators: ==, <, <=, >, >=, !=

Logical expressions evaluate to 1 (true) or 0 (false)

Logical operators: ! (not), && (and), || (or)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

55

Quick Review (2 of 3)

Two selection structures are one-way selection and two-way selection

The expression in an if or if...else structure is usually a logical expression

No stand-alone else statement exists in C++

Every else has a related if

A sequence of statements enclosed between braces, { and }, is called a compound statement or a block of statements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

56

Quick Review (3 of 3)

Using assignment in place of the equality operator creates a semantic error

The execution of a switch structure handles multiway selection

The execution of a break statement ends a switch statement

Use assert to terminate a program if certain conditions are not met

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

57

9781337117562_ppt_ch05.pptx

Chapter 5

Control Structures II (Repetition)

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn about repetition (looping) control structures

Learn how to use a while loop in a program

Explore how to construct and use counter-controlled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures

Learn how to use a for loop in a program

Learn how to use a do…while loop in a program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Examine break and continue statements

Discover how to form and use nested control structures

Learn how to avoid bugs by avoiding patches

Learn how to debug loops

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Why Is Repetition Needed?

Repetition allows efficient use of variables

It is possible to input, add, and average multiple numbers using a limited number of variables

Consider the code to determine the average number of calories burned each day doing regular exercise

Method 1: Declare a variable for each day and enter the number of calories burned, add the values and store in a variable for the week’s total, and divide the total by 7 to find the average

Method 2: Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers (only two variables needed)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

while Looping (Repetition) Structure (1 of 3)

A while loop is one of three repetition, or looping structures in C++

Syntax of the while statement

The statement can be simple or compound

The expression acts as a decision maker and is usually a logical expression

The statement is called the body of the loop

The parentheses are part of the syntax

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

while Looping (Repetition) Structure (2 of 3)

FIGURE 5-1 while loop

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

The expression provides an entry condition to the loop

The statement (body of the loop) continues to execute until the expression is no longer true

An infinite loop continues to execute endlessly

‹#›

6

while Looping (Repetition) Structure (3 of 3)

The preceding while loop produces the following output:

0 5 10 15 20

The variable i in Example 5-1 is called the loop control variable (LCV)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

while Looping (Repetition) Structure (cont’d.)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Case 1: Counter-Controlled while Loops

When you know exactly how many times the statements need to be executed

Use a counter-controlled while loop

counter = 0; //initialize the loop control variable

while (counter < N) //test the loop control variable

{

.

.

.

counter++; //update the loop control variable

.

.

.

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Case 2: Sentinel-Controlled while Loops

A sentinel variable is tested in the condition

The loop ends when the sentinel is encountered

The following is an example of a sentinel-controlled while loop:

cin >> variable; //initialize the loop control variable

while (variable != sentinel) //test the loop control variable

{

.

.

.

cin >> variable; //update the loop control variable

.

.

.

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Example 5-5: Telephone Digits

Example 5-5 provides an example of a sentinel-controlled loop

The program converts uppercase letters to their corresponding telephone digit

The sentinel value is #

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Case 3: Flag-Controlled while Loops

Flag-controlled while loop: uses a bool variable to control the loop

isFound = false; //initialize the loop control variable

while (!isFound) //test the loop control variable

{

.

.

.

if (expression)

isFound = true; //update the loop control variable

.

.

.

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Number Guessing Game

Example 5-6 implements a number guessing game using a flag-controlled while loop

Uses the function rand of the header file cstdlib to generate a random number

rand() returns an int value between 0 and 32767

To convert to an integer >= 0 and < 100:

rand() % 100

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Case 4: EOF-Controlled while Loops (1 of 2)

An end-of-file (EOF)-controlled while loop is a good choice when it is difficult to select a sentinel value

The logical value returned by cin can determine if there is no more input

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Case 4: EOF-Controlled while Loops (2 of 2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

eof Function

The function eof can determine the end of file status

eof is a member of data type istream

Syntax for the function eof

istreamVar is an input stream variable, such as cin

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

More on Expressions in while Statements

The expression in a while statement can be complex

Example

while ((noOfGuesses < 5) && (!isGuessed))

{

. . .

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Programming Example: Fibonacci Number (1 of 3)

Consider the following sequence of numbers:

1, 1, 2, 3, 5, 8, 13, 21, 34, ....

Called the Fibonacci sequence

Given the first two numbers of the sequence (say, a1 and a2)

nth number an, n >= 3, of this sequence is given by: an = an-1 + an-2

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Programming Example: Fibonacci Number (2 of 3)

Fibonacci sequence

nth Fibonacci number

a2 = 1

a1 = 1

Determine the nth number an, n >= 3

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Programming Example: Fibonacci Number (3 of 3)

Suppose a2 = 6 and a1 = 3

a3 = a2 + a1 = 6 + 3 = 9

a4 = a3 + a2 = 9 + 6 = 15

Write a program that determines the nth Fibonacci number, given the first two numbers

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Programming Example: Input and Output

Input: first two Fibonacci numbers and the desired Fibonacci number

Output: nth Fibonacci number

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Programming Example: Problem Analysis and Algorithm Design

Algorithm

Get the first two Fibonacci numbers

Get the desired Fibonacci number

Get the position, n, of the number in the sequence

Calculate the next Fibonacci number

Add the previous two elements of the sequence

Repeat Step 3 until the nth Fibonacci number is found

Output the nth Fibonacci number

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Programming Example: Variables

int previous1; //variable to store the first Fibonacci number

int previous2; //variable to store the second Fibonacci number

int current; //variable to store the current Fibonacci number

int counter; //loop control variable

int nthFibonacci; //variable to store the desired

//Fibonacci number

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Programming Example: Main Algorithm (1 of 4)

Prompt the user for the first two numbers—that is, previous1 and previous2

Read (input) the first two numbers into previous1 and previous2

Output the first two Fibonacci numbers

Prompt the user for the position of the desired Fibonacci number

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Programming Example: Main Algorithm (2 of 4)

Read the position of the desired Fibonacci number into nthFibonacci

if (nthFibonacci == 1) The desired Fibonacci number is the first Fibonacci number; copy the value of previous1 into current

else if (nthFibonacci == 2) The desired Fibonacci number is the second Fibonacci number; copy the value of previous2 into current

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Programming Example: Main Algorithm (3 of 4)

else calculate the desired Fibonacci number as follows:

Start by determining the third Fibonacci number

Initialize counter to 3 to keep track of the calculated Fibonacci numbers.

Calculate the next Fibonacci number, as follows: current = previous2 + previous1;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Programming Example: Main Algorithm (4 of 4)

Assign the value of previous2 to previous1

Assign the value of current to previous2

Increment counter

Repeat until Fibonacci number is calculated:

while (counter <= nthFibonacci)

{

current = previous2 + previous1;

previous1 = previous2;

previous2 = current;

counter++;

}

Output the nth Fibonacci number, which is current

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

for Looping (Repetition) Structure (1 of 7)

for loop: called a counted or indexed for loop

Syntax of the for statement

The initial statement, loop condition, and update statement are called for loop control statements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

for Looping (Repetition) Structure (2 of 7)

FIGURE 5-2 for loop

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

for Looping (Repetition) Structure (3 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

for Looping (Repetition) Structure (4 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

for Looping (Repetition) Structure (5 of 7)

The following is a semantic error:

The following is a legal (but infinite) for loop:

for (;;)

cout << "Hello" << endl;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

for Looping (Repetition) Structure (6 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

for Looping (Repetition) Structure (7 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

do…while Looping (Repetition) Structure (1 of 6)

Syntax of a do...while loop

The statement executes first, and then the expression is evaluated

As long as expression is true, loop continues

To avoid an infinite loop, body must contain a statement that makes the expression false

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

do…while Looping (Repetition) Structure (2 of 6)

The statement can be simple or compound

Loop always iterates at least once

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

do…while Looping (Repetition) Structure (3 of 6)

FIGURE 5-3 do. . .while loop

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

do…while Looping (Repetition) Structure (4 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

do…while Looping (Repetition) Structure (5 of 6)

Note that while and for loops are pretest loops

It is possible that these loops many never activate due to entry conditions

In contrast, do. . .while loops are posttest loops

These loops always execute at least once

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

do…while Looping (Repetition) Structure (6 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Choosing the Right Looping Structure

All three loops have their place in C++

If you can determine in advance the number of repetitions needed, the for loop is the correct choice

If you do not know and cannot determine in advance the number of repetitions needed, and it could be zero, use a while loop

If you do not know and cannot determine in advance the number of repetitions needed, and it is at least one, use a do...while loop

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

break and continue Statements (1 of 2)

break and continue alter the flow of control

break statement is used for two purposes:

To exit early from a loop

To skip the remainder of a switch structure

After break executes, the program continues with the first statement after the structure

A break statement in a loop can eliminate the use of certain (flag) variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

42

break and continue Statements (2 of 2)

continue is used in while, for, and do…while structures

When executed in a loop

It skips remaining statements and proceeds with the next iteration of the loop

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

43

Nested Control Structures (1 of 2)

To create the following pattern:

*

**

***

****

*****

We can use the following code:

for (i = 1; i <= 5; i++) //Line 1

{ //Line 2

for (j = 1; j <= i; j++) //Line 3

cout << "*"; //Line 4

cout << endl; //Line 5

} //Line 6

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

44

Nested Control Structures (2 of 2)

What is the result if we replace the first for statement with this?

for (i = 5; i >= 1; i--)

Answer:

*****

****

***

**

*

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

45

Avoiding Bugs by Avoiding Patches

A software patch is a piece of code written on top of an existing piece of code

Intended to fix a bug in the original code

Some programmers address the symptom of the problem by adding a software patch

A programmer should instead resolve the underlying issue

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

46

Debugging Loops

Loops are harder to debug than sequence and selection structures

Use a loop invariant

Set of statements that remains true each time the loop body is executed

The most common error associated with loops is off-by-one

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

47

Quick Review (1 of 3)

C++ has three looping (repetition) structures:

while, for, and do…while

while, for, and do are reserved words

while and for loops are called pretest loops

do...while loop is called a posttest loop

while and for may not execute at all, but do...while always executes at least once

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

48

Quick Review (2 of 3)

In a while loop:

The expression is the decision maker

The statement is the body of the loop

A while loop can be:

Counter-controlled

Sentinel-controlled

EOF-controlled

In the Windows console environment, the end-of-file marker is entered using Ctrl+z

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

49

Quick Review (3 of 3)

A for loop simplifies the writing of a counter-controlled while loop

Putting a semicolon at the end of the for loop is a semantic error

Executing a break statement in the body of a loop immediately terminates the loop

Executing a continue statement in the body of a loop skips to the next iteration

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

50

9781337117562_ppt_ch06.pptx

Chapter 6

User-Defined Functions

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn about standard (predefined) functions and discover how to use them in a program

Learn about user-defined functions

Examine value-returning functions , including actual and formal parameters

Explore how to construct and use a value-returning, user-defined function in a program

Learn about function prototypes

Learn how to construct and use void functions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Discover the difference between value and reference parameters

Explore reference parameters and value-returning functions

Learn about the scope of an identifier

Examine the difference between local and global identifiers

Discover static variables

Learn how to debug programs using drivers and stubs

Learn function overloading

Explore functions with default parameters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Introduction

Functions allow complicated programs to be divided into manageable pieces

Functions are often called modules

They are like miniature programs that can be combined to form larger programs

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Predefined Functions (1 of 2)

In C++, a function is similar to that of a function in algebra

It has a name

It does some computation

Some of the predefined mathematical functions are:

pow(x, y)

sqrt(x)

floor(x)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Predefined Functions (2 of 2)

Predefined functions are organized into separate libraries

I/O functions are in iostream header

Math functions are in cmath header

To use predefined functions, you must include the header file using an include statement

See Table 6-1 in the text for some common predefined functions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

User-Defined Functions

Value-returning functions have a return type

Return a value of a specific data type using the return statement

Void functions do not have a return type

Do not use a return statement to return a value

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Value-Returning Functions (1 of 3)

To use these functions, you must:

Include the appropriate header file in your program using the include statement

Know the following items:

Name of the function

Number of parameters, if any

Data type of each parameter

Data type of the value returned, called the type of the function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Value-Returning Functions (2 of 3)

Can use the value returned by a value-returning function by:

Saving it for further calculation

Using it in some calculation

Printing it

A value-returning function is used:

In an assignment

As a parameter in a function call

In an output statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Value-Returning Functions (3 of 3)

Heading (or function header): the first line of the function

Example: int abs(int number)

The body is the function’s code that accomplishes the task

Formal parameter: a variable declared in the heading

Example: number

Actual parameter: a variable or expression listed in a call to a function

Example: x = pow(u, v)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Syntax: Value-Returning Function

Syntax

functionType is also called the data type or return type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Syntax: Formal Parameter List

FIGURE 6-1 Various parts of the function abs

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Function Call

Syntax to call a value-returning function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Syntax: Actual Parameter List

The syntax of the actual parameter list is:

The formal parameter list can be empty

A call to a value-returning function with an empty formal parameter list is:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

return Statement

A function returns its value via the return statement

It passes this value outside the function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Syntax: return Statement (1 of 2)

The return statement has this syntax:

In C++, return is a reserved word

When a return statement executes

The function immediately terminates

Control goes back to the caller

When a return statement executes in the function main, the program terminates

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Syntax: return Statement (2 of 2)

FIGURE 6-2 Various parts of the function larger

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Function Prototype

A function prototype is the function heading without the body of the function

The general syntax of the function prototype of a value-returning function is:

It is not necessary to specify the variable name in the parameter list

The data type of each parameter must be specified

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Value-Returning Functions: Some Peculiarities (1 of 2)

int secret(int x)

{

if (x > 5) //Line 1

return 2 * x; //Line 2

}

A correct definition of the function secret is:

int secret(int x)

{

if (x > 5) //Line 1

return 2 * x; //Line 2

return x; //Line 3

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Value-Returning Functions: Some Peculiarities (2 of 2)

Examples pointing out that the return statement only returns one value

return x, y; //only the value of y will be returned

int funcRet1()

{

int x = 45;

return 23, x; //only the value of x is returned

}

int funcRet2(int z)

{

int a = 2;

int b = 3;

return 2 * a + b, z + b;

//only the value of z + b is returned

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

More Examples of Value-Returning Functions (1 of 2)

char courseGrade(int score)

{

switch (score / 10)

{

case 0:

case 1:

case 2:

case 3:

case 4:

case 5:

return 'F';

case 6:

return 'D';

case 7:

return 'C';

case 8:

return 'B';

case 9:

case 10:

return 'A';

}

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

More Examples of Value-Returning Functions (2 of 2)

In addition to Example 6-3 courseGrade, other examples are given in the text

Example 6-4 (rolling a pair of dice)

Example 6-5 (Fibonacci number)

Example 6-6 (palindrome)

Example 6-7 (cable company)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Flow of Compilation and Execution (1 of 2)

Execution always begins at the first statement in the function main

Other functions are executed only when called

Function prototypes appear before any function definition

The compiler translates these first

The compiler can then correctly translate a function call

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Flow of Compilation and Execution (2 of 2)

A function call transfers control to the first statement in the body of the called function

When the end of a called function is executed, control is passed back to the point immediately following the function call

A function’s returned value replaces the function call statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Void Functions (1 of 4)

User-defined void functions can be placed either before or after the function main

If user-defined void functions are placed after the function main

The function prototype must be placed before the function main

A void function does not have a return type

A return statement without any value is typically used to exit the function early

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Void Functions (2 of 4)

Formal parameters are optional

A call to a void function is a stand-alone statement

The function definition of void functions with parameters has the following syntax:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Void Functions (3 of 4)

Formal parameter list syntax

Function call syntax

Actual parameter list syntax

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

Void Functions (4 of 4)

Two types of formal parameters

Value parameter: a formal parameter that receives a copy of the content of corresponding actual parameter

Reference parameter: a formal parameter that receives the location (memory address) of the corresponding actual parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

Value Parameters

If a formal parameter is a value parameter, the value of the corresponding actual parameter is copied into it

A formal parameter has its own copy of the data

During program execution, a formal parameter manipulates the data stored in its own memory space

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

Reference Variables as Parameters (1 of 2)

If a formal parameter is a reference parameter:

It receives the memory address of the corresponding actual parameter

During program execution to manipulate data:

Changes to a formal parameter will change the corresponding actual parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Reference Variables as Parameters (2 of 2)

Reference parameters are useful in three situations:

When changing the actual parameter

When returning more than one value

When passing the address would save memory space and time

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

Value and Reference Parameters and Memory Allocation (1 of 2)

When a function is called:

Memory for its formal parameters and its local variables is allocated in the function data area

For a value parameter, the actual parameter’s value is copied into the formal parameter’s memory cell

Changes to the formal parameter do not affect the actual parameter’s value

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

Value and Reference Parameters and Memory Allocation (2 of 2)

For a reference parameter, the actual parameter’s address passes to the formal parameter

Both formal and actual parameters refer to the same memory location

During execution, any change made to the formal parameter’s value immediately changes the actual parameter’s value

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

Reference Parameters and Value-Returning Functions

Can also use reference parameters in a value-returning function

Not recommended

By definition, a value-returning function returns a single value via return statement

If a function needs to return more than one value, change it to a void function and use reference parameters to return the values

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

Scope of an Identifier

Scope of an identifier: where in the program the identifier is accessible

Local identifier: identifiers declared within a function (or block)

Global identifier: identifiers declared outside of every function definition

C++ does not allow nested functions

Definition of one function cannot be included in the body of another function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

Rules Applied When an Identifier is Accessed (1 of 2)

Global identifiers are accessible by a function or block if:

The identifier is declared before the function definition (block)

The function name different from the identifier

All parameters to the function have different names than the identifier name

All local identifiers have different names than the identifier name

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Rules Applied When an Identifier is Accessed (2 of 2)

(Nested block) – an identifier declared within a block is accessible:

From its point of declaration to the end of the block in which it is declared

Within nested blocks if no identifier with the same name exists

The scope of a function name is similar to the scope of an identifier declared outside any block

The function name scope is the same as the global variable scope

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Other Notes about Global Variables

Some compilers initialize global variables to default values

The scope resolution operator in C++ is ::

By using the scope resolution operator:

A global variable declared before the definition of a function (or block) can be accessed by the function (or block) even if the function (or block) has an identifier with the same name as the global variable

To access a global variable declared after the definition of a function, the function must not contain any identifier with the same name

Reserved word extern indicates that a global variable has been declared elsewhere

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Global Variables, Named Constants, and Side Effects

Using global variables causes side effects

A function that uses global variables is not independent

If more than one function uses the same global variable:

It can be difficult to debug problems with the code

Problems caused in one area of the program may appear to be from another area

Global named constants have no side effects

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

39

Static and Automatic Variables (1 of 2)

Automatic variable: memory is allocated at block entry and deallocated at block exit

By default, variables declared within a block are automatic variables

Static variable: memory remains allocated as long as the program executes

Global variables declared outside of any block are static variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Static and Automatic Variables (2 of 2)

Declare a static variable within a block by using the reserved word static

The syntax for declaring a static variable is:

Static variables declared within a block are local to the block

Have same scope as any other local identifier in that block

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

Debugging: Using Drivers and Stubs

A driver program is a separate program used to test a function

When results calculated by one function are needed in another function, use a function stub

A function stub is a function that is not fully coded

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

42

Function Overloading: An Introduction

In a C++ program, several functions can have the same name

Function overloading (or overloading a function name) occurs when creating several functions with the same name

Two functions are said to have different formal parameter lists if both functions have either:

A different number of formal parameters

If the number of formal parameters is the same, but the data type of the formal parameters differs in at least one position

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

43

Function Overloading

Overloaded functions must have different formal parameter lists

The signature: the name and formal parameter list of the function

Does not include the return type of the function

The parameter list supplied in a call to an overloaded function determines which function is executed

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

44

Functions with Default Parameters (1 of 2)

In a function call, the number of actual and formal parameters must be the same

C++ relaxes this condition for functions with default parameters

Can specify the value of a default parameter in the function prototype

If you do not specify the value for a default parameter when calling the function, the default value is used

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

45

Functions with Default Parameters (2 of 2)

All default parameters must be the rightmost parameters of the function

If a default parameter value is not specified:

You must omit all of the arguments to its right

Default values can be constants, global variables, or function calls

Cannot assign a constant value as a default value to a reference parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

46

Quick Review (1 of 4)

Functions (modules) divide a program into manageable tasks

C++ provides standard, predefined functions

Two types of user-defined functions: value-returning functions and void functions

Variables defined in a function heading are called formal parameters

Expressions, variables, or constant values in a function call are called actual parameters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

47

Quick Review (2 of 4)

Function heading and the body of the function are called the definition of the function

A value-returning function returns its value via the return statement

A prototype is the function heading without the body of the function

User-defined functions execute only when they are called

Void functions do not have a data type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

48

Quick Review (3 of 4)

There are two types of formal parameters

A value parameter receives a copy of its corresponding actual parameter

A reference parameter receives the memory address of its corresponding actual parameter

Variables declared within a function (or block) are called local variables

Variables declared outside of every function definition (and block) are global variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

49

Quick Review (4 of 4)

An automatic variable is a variable for which memory is allocated on function/block entry and deallocated on function/block exit

A static variable is a variable for which memory remains allocated throughout the execution of the program

C++ functions can have default parameters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

50

9781337117562_ppt_ch07.pptx

Chapter 7

User-Defined Simple Data Types, Namespaces, and the string Type

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn how to create and manipulate your own simple data type—called the enumeration type

Explore how the assignment statement, and arithmetic and relational operators work with enum types

Learn how to use for loops with enum types

Learn how to input data into an enum type

Learn how to output data stored in an enum type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Explore how to write functions to process enum types

Learn how to declare variables when defining the enumeration type

Become familiar with anonymous types

Become familiar with the typedef statement

Learn about the namespace mechanism

Explore the string data type, and learn how to use string functions to manipulate strings

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Enumeration Type (1 of 5)

A data type is a set of values with a set of operations on them

Enumeration type is a simple data type created by the programmer

To define an enumeration type, you need:

A name for the data type

A set of values for the data type

A set of operations on the values

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Enumeration Type (2 of 5)

You can specify the name and the values, but not the operations

The syntax for enumeration type is:

value1, value2, … are identifiers called enumerators

List specifies the ordering:

value1 < value2 < value3 <...

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Enumeration Type (3 of 5)

The enumeration type is an ordered set of values

Default value assigned to enumerators starts at 0

A value used in one enumeration type cannot be used by another in the same block

Same rules apply to enumeration types declared outside of any blocks

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Enumeration Type (4 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Enumeration Type (5 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Declaring Variables

Syntax

Example

enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL};

Can declare variables such as:

sports popularSport, mySport;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Assignment

Values can be stored in enumeration data types:

popularSport = FOOTBALL;

Stores FOOTBALL into popularSport

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Operations on Enumeration Types

No arithmetic operations are allowed on enumeration types

mySport = popularSport + 2; //illegal

popularSport = FOOTBALL + SOCCER; //illegal

popularSport = popularSport * 2; //illegal

++ and -- are illegal, too

popularSport++; //illegal

popularSport--; //illegal

The solution is applying the cast operator

popularSport = FOOTBALL;

popularSport = static_cast<sports>(popularSport + 1);

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Relational Operators

An enumeration type is an ordered set of values:

FOOTBALL <= SOCCER is true

HOCKEY > BASKETBALL is true

BASEBALL < FOOTBALL is false

An enumeration type is an integral data type and can be used in loops:

for (mySport = BASKETBALL; mySport <= SOCCER; mySport = static_cast<sports>(mySport + 1))

.

.

.

This for loop has five iterations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Input /Output of Enumeration Types

An enumeration type cannot be input/output (directly)

Can input and output indirectly – refer to code segments below:

enum courses {ALGEBRA, BASIC, PYTHON, CPP, PHILOSOPHY, ANALYSIS, CHEMISTRY, HISTORY};

courses registered;

switch (ch1)

{

case 'a':

if (ch2 == 'l')

registered = ALGEBRA;

else

registered = ANALYSIS;

break;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Functions and Enumeration Types

Enumeration types can be passed as parameters to functions either by value or by reference

A function can return a value of the enumeration type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Declaring Variables When Defining the Enumeration Type

Can declare variables of an enumeration type when you define an enumeration type:

enum grades {A, B, C, D, F} courseGrade;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Anonymous Data Types (1 of 2)

Anonymous type values are directly specified in the declaration, with no type name

Example:

enum {BASKETBALL, FOOTBALL, BASEBALL, HOCKEY} mySport;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Anonymous Data Types (2 of 2)

Drawbacks:

Cannot pass/return an anonymous type to/from a function

Values used in one type can be used in another, but are treated differently:

enum {ENGLISH, FRENCH, SPANISH, GERMAN, RUSSIAN} languages;

enum {ENGLISH, FRENCH, SPANISH, GERMAN, RUSSIAN} foreignLanguages;

This statement is illegal:

languages = foreignLanguages; //Illegal

Best practices: to avoid confusion, define an enumeration type first, then declare variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

typedef Statement (1 of 2)

The typedef statement is used to create synonyms or aliases to a data type

The syntax of the typedef statement is:

typedef does not create any new data types

Only creates an alias to an existing data type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

typedef Statement (2 of 2)

The typedef statement is used to create synonyms or aliases to a data type

The syntax of the typedef statement is:

typedef does not create any new data types

Only creates an alias to an existing data type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Namespaces (1 of 6)

ANSI/ISO standard C++ was officially approved in July 1998

Most recent compilers are compatible with ANSI/ISO standard C++

For the most part, standard C++ and ANSI/ISO standard C++ are the same

However, ANSI/ISO Standard C++ has some features not available in Standard C++

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Namespaces (2 of 6)

Global identifiers in a header file used in a program become global in the program

A syntax error occurs if a program’s identifier has the same name as a global identifier in the header file

The same problem can occur with third-party libraries

Common solution: third-party vendors begin their global identifiers with _ (underscore)

Do not begin identifiers in your program with _

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Namespaces (3 of 6)

ANSI/ISO Standard C++ attempts to solve this problem with the namespace mechanism

The general syntax of the statement namespace is:

where members consist of variable declarations, named constants, functions, or another namespace

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Namespaces (4 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Namespaces (5 of 6)

A namespace member has scope local to the namespace

A namespace member can be accessed outside the namespace

The general syntax for accessing a namespace member is:

ANSI/ISO Standard C++ provides the use of the statement using

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Namespaces (6 of 6)

Examples with namespaces

globalType::RATE

using namespace globalType;

using globalType::RATE;

After the using statement, it is not necessary to put the namespace_name:: before the namespace member

Unless a namespace member and a global identifier or a block identifier have the same name

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

string Type

To use data type string, a program must include the header file string

A string is a sequence of zero or more characters

The first character is in position 0

The second character is in position 1, etc.

Binary operator + performs the string concatenation operation

Array subscript operator [] allows access to an individual character in a string

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Additional string Operations

The data type string has a data type, string::size_type, and a named constant, string::npos, defined as follows:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

string::size_type An unsigned integer (data) type
string::npos The maximum value of the (data) type string::size_type, a number such as 4294967295 on many machines

‹#›

27

Example 7-18: swap Function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

Quick Review (1 of 3)

Enumeration type: set of ordered values

Reserved word enum creates an enumeration type

No arithmetic operations are allowed on the enumeration type

Relational operators can be used with enum values

Enumeration type values cannot be input or output directly

Enumeration types can be passed as parameters to functions by value or by reference

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

Quick Review (2 of 3)

Anonymous type: a variable’s values are specified without any type name

Reserved word typedef creates synonyms or aliases to previously defined data types

The namespace mechanism is a feature of ANSI/ISO Standard C++

A namespace member is usually a named constant, variable, function, or another namespace

Scope of a namespace member is local to namespace

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Quick Review (3 of 3)

using statement simplifies access to namespace members

A string is a sequence of zero or more characters

Strings in C++ are enclosed in ""

The first character of a string is in position 0

In C++, [] is the array subscript operator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

9781337117562_ppt_ch08.pptx

Chapter 8

Arrays and Strings

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 3)

In this chapter, you will:

Learn the reasons for arrays

Explore how to declare and manipulate data into arrays

Understand the meaning of ‘‘array index out of bounds’’

Learn how to declare and initialize arrays

Become familiar with the restrictions on array processing

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 3)

Discover how to pass an array as a parameter to a function

Learn how to search an array

Learn how to sort an array

Become aware of auto declarations

Learn about range-based for loops

Learn about C-strings

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Objectives (3 of 3)

Examine the use of string functions to process C-strings

Discover how to input data into—and output data from—a C-string

Learn about parallel arrays

Discover how to manipulate data in a two-dimensional array

Learn about multidimensional arrays

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Introduction

Simple data type: variables of these types can store only one value at a time

Structured data type: a data type in which each data item is a collection of other data items

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Arrays

Array: a collection of a fixed number of components, all of the same data type

One-dimensional array: components are arranged in a list form

Syntax for declaring a one-dimensional array

intExp: any constant expression that evaluates to a positive integer

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Accessing Array Components (1 of 3)

General syntax

indexExp: called the index

An expression with a nonnegative integer value

Value of the index is the position of the item in the array

[]: array subscripting operator

Array index always starts at 0

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Accessing Array Components (2 of 3)

This statement declares an array of 10 components: int list[10];

FIGURE 8-3 Array list

list[5] = 34; stores 34 in list[5], the sixth component of the array list

FIGURE 8-4 Array list after execution of the statement list[5]= 34;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Accessing Array Components (3 of 3)

list[3] = 10;

list[6] = 35;

list[5] = list[3] + list[6];

FIGURE 8-5 Array list after execution of the statements list[3]= 10;, list[6]= 35;, and list[5] = list[3] + list[6];

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Processing One-Dimensional Arrays (1 of 3)

Basic operations on a one-dimensional array include:

Initializing

Inputting data

Outputting data stored in an array

Finding the largest and/or smallest element

Each operation requires ability to step through elements of the array

Easily accomplished using a loop

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Processing One-Dimensional Arrays (2 of 3)

Given the declaration:

int list[100]; //array of size 100

int i;

Use a for loop to access array elements:

for (i = 0; i < 100; i++) //Line 1

cin >> list[i]; //Line 2

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Processing One-Dimensional Arrays (3 of 3)

Refer to Example 8-3 in the text, which shows how loops are used to process arrays

Initializing an array

Reading data into an array

Printing an array

Finding the sum and average of an array

Finding the largest element in an array

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Array Index Out of Bounds

The index of an array is in bounds if the index is between 0 and ARRAY_SIZE - 1

Otherwise, the index is out of bounds

In C++, there is no guard against indices that are out of bounds

This check is solely the programmer’s responsibility

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Array Initialization During Declaration

Arrays can be initialized during declaration

Values are placed between curly braces

Example 1

double sales[5] = {12.25, 32.50, 16.90, 23, 45.68}

Example 2: the array size is determined by the number of initial values in the braces if the array is declared without size specified

double sales[] = {12.25, 32.50, 16.90, 23, 45.68}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Partial Initialization of Arrays During Declaration

The statement:

int list[10] = {0};

Declares an array of 10 components and initializes all of them to zero

The statement (an example of partial initialization of an array during declaration):

int list[10] = {8, 5, 12};

Declares an array of 10 components and initializes list[0] to 8, list[1] to 5, list[2] to 12

All other components are initialized to 0

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Some Restrictions on Array Processing

Aggregate operation: any operation that manipulates the entire array as a single unit

Not allowed on arrays in C++

Example

int myList[5] = {0, 4, 8, 12, 16}; //Line 1

int yourList[5]; //Line 2

yourList = myList; //illegal

Solution

for (int index = 0; index < 5; index++)

yourList[index] = myList[index];

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Arrays as Parameters to Functions

Arrays are passed by reference only

Do not use symbol & when declaring an array as a formal parameter

The size of the array is usually omitted in the array parameter

If provided, it is ignored by the compiler

The following example illustrates a function header, which includes an array parameter and a parameter specifying the number of elements in the array:

void initialize(int list[], int listSize)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Constant Arrays as Formal Parameters

Can prevent a function from changing the actual parameter when passed by reference

Use const in the declaration of the formal parameter

Example

void example(int x[], const int y[], int sizeX, int sizeY)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Base Address of an Array and Array in Computer Memory

The base address of an array is the address (memory location) of the first array component

If list is a one-dimensional array, its base address is the address of list[0]

When an array is passed as a parameter, the base address of the actual array is passed to the formal parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Functions Cannot Return a Value of the Type Array

C++ does not allow functions to return a value of type array

Refer to Example 8-6 in the text

Functions sumArray and indexLargestElement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Integral Data Type and Array Indices

C++ allows any integral type to be used as an array index

Improves code readability

The following code illustrates improved readability:

enum paintType {GREEN, RED, BLUE, BROWN, WHITE, ORANGE,

YELLOW};

double paintSale[7];

paintType paint;

for (paint = GREEN; paint <= YELLOW;

paint = static_cast<paintType>(paint + 1))

paintSale[paint] = 0.0;

paintSale[RED] = paintSale[RED] + 75.69;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Other Ways to Declare Arrays

Example 1

const int NO_OF_STUDENTS = 20;

int testScores[NO_OF_STUDENTS];

Example 2

const int SIZE = 50; //Line 1

typedef double list[SIZE]; //Line 2

list yourList; //Line 3

list myList; //Line 4

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Searching an Array for a Specific Item

Sequential search (or linear search)

Searching a list for a given item, starting from the first array element

Compare each element in the array with value that is being searched

Continue the search until item is found or no more data is left in the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Sorting

Selection sort: rearrange the list by selecting an element and moving it to its proper position

Steps for a selection sort:

Find the smallest element in the unsorted portion of the list

Move it to the top of the unsorted portion by swapping with the element currently there

Start again with the rest of the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Selection Sort

FIGURE 8-10 Elements of list during the first iteration

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Auto Declaration and Range-Based for Loops

C++11 allows auto declaration of variables

Data type does not need to be specified

auto num = 15;

The type of num will be int

Range-based for loop

double list[25];

double sum;

sum = 0;

for (double num : list) // read as “for each num in list”

sum = sum + num;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

C-Strings (Character Arrays) (1 of 3)

A character array is an array whose components are of type char

C-strings are null-terminated ('\0') character arrays

Examples

'A' is the character A

"A" is the C-string A

Note: "A" represents two characters, 'A' and '\0'

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

C-Strings (Character Arrays) (2 of 3)

This is an example of a C-string declaration:

char name[16];

Since C-strings are null terminated and name has 16 components, the largest string it can store has 15 characters

If you store a string whose length is less than the array size, the last components are unused

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

C-Strings (Character Arrays) (3 of 3)

The size of an array can be omitted if the array is initialized during declaration

char name[] = "John";

Declares an array of length 5 and stores the C-string "John" in the array

Useful string manipulation functions include:

strcpy

strncpy

strcmp

strlen

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

String Comparison

C-strings are compared character by character using the collating sequence of the system

Use the function strcmp

If using the ASCII character set:

"Air" < "Boat"

"Air" < "An"

"Bill" < "Billy"

"Hello" < "hello"

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Reading and Writing Strings

Most rules for arrays also apply to C-strings (which are character arrays)

Aggregate operations, such as assignment and comparison, are not allowed on arrays

C++ does allow aggregate operations for the input and output of C-strings

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

String Input

This is an example of string input:

cin >> name;

Stores the next input C-string into name

To read strings with blanks, use the function get:

cin.get(str, m+1);

When executed , the statement stores the next m characters into str, but the newline character is not stored in str

If input string has fewer than m characters, reading stops at the newline character

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

String Output

Example

cout << name;

Outputs the content of name on the screen

<< continues to write the contents of name until it finds the null character

If name does not contain the null character, then strange output may occur since << continues to output data from memory adjacent to name until a '\0' is found

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

Specifying Input/Output Files at Execution Time

User can specify the name of an input and/or output file at execution time

cout << "Enter the input file name: ";

cin >> fileName;

infile.open(fileName); //open the input file

.

.

.

cout << "Enter the output file name: ";

cin >> fileName;

outfile.open(fileName); //open the output file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

string Type and Input/Output Files

Argument to the open function must be a null-terminated string (a C-string)

If using a string variable for the name of an I/O file, the value must first be converted to a C-string before calling open

Use the c_str function to convert

The syntax to use the function c_str is:

strVar.c_str()

Where strVar is a variable of type string

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

Parallel Arrays

Two (or more) arrays are called parallel if their corresponding components hold related information

The following example illustrates two parallel arrays:

int studentId[50];

char courseGrade[50];

With the following sample data to enter into the arrays:

studentId courseGrade

23456 A

86723 B

22356 C

92733 B

11892 D

.

.

.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Two- and Multidimensional Arrays

Two-dimensional array: a collection of a fixed number of components (of the same type) arranged in two dimensions

Sometimes called matrices or tables

Declaration syntax

intExp1 and intExp2 are expressions with positive integer values specifying the number of rows and columns in the array

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Accessing Array Components (1 of 2)

Syntax to access a component in a two-dimensional array

Where indexExp1 and indexExp2 are expressions with positive integer values, and specify the row and column position

Example: sales[5][3] = 25.75;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Accessing Array Components (2 of 2)

FIGURE 8-14 sales[5][3]

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

39

Two-Dimensional Array Initialization During Declaration

Two-dimensional arrays can be initialized when they are declared

Elements of each row are enclosed within braces and separated by commas

All rows are enclosed within braces

For number arrays, unspecified elements are set to 0

An example of two-dimensional array initialization is shown below:

int board[4][3] = {{2, 3, 1},

{15, 25, 13},

{20, 4, 7},

{11, 18, 14}};

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Two-Dimensional Arrays and Enumeration Types

Enumeration types can be used for array indices

const int NUMBER_OF_ROWS = 6;

const int NUMBER_OF_COLUMNS = 5;

enum carType {GM, FORD, TOYOTA, BMW, NISSAN, VOLVO};

enum colorType {RED, BROWN, BLACK, WHITE, GRAY};

int inStock[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

Processing Two-Dimensional Arrays

Ways to process a two-dimensional array:

Process a single element

Process the entire array

Process a single row at a time, called row processing

Process a single column at a time, called column processing

Each row and each column of a two-dimensional array is a one-dimensional array

To process, use algorithms similar to processing one-dimensional arrays

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

42

Initialization

An example initializing row number 4 (fifth row) to 0:

row = 4;

for (col = 0; col < NUMBER_OF_COLUMNS; col++)

matrix[row][col] = 0;

An example initializing the entire matrix to 0

for (row = 0; row < NUMBER_OF_ROWS; row++)

for (col = 0; col < NUMBER_OF_COLUMNS; col++)

matrix[row][col] = 0;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

43

Print

Use a nested loop to output the components of a two dimensional array

for (row = 0; row < NUMBER_OF_ROWS; row++)

for (col = 0; col < NUMBER_OF_COLUMNS; col++)

cout << setw(5) << matrix[row][col] << " ";

cout << endl;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

44

Input

An example of adding input to row number 4 (fifth row):

row = 4;

for (col = 0; col < NUMBER_OF_COLUMNS; col++)

cin >> matrix[row][col];

An example of adding input to each component of matrix:

for (row = 0; row < NUMBER_OF_ROWS; row++)

for (col = 0; col < NUMBER_OF_COLUMNS; col++)

cin >> matrix[row][col];

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

45

Sum by Row

The following example shows how to find the sum of row number 4:

sum = 0;

row = 4;

for (col = 0; col < NUMBER_OF_COLUMNS; col++)

sum = sum + matrix[row][col];

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

46

Sum by Column

The following example illustrates finding the sum of each individual column:

//Sum of each individual row

for (row = 0; row < NUMBER_OF_ROWS; row++)

{

sum = 0;

for (col = 0; col < NUMBER_OF_COLUMNS; col++)

sum = sum + matrix[row][col];

cout << "Sum of row " << row + 1 << " = " << sum << endl;

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

47

Largest Element in Each Row and Each Column

The following example finds the largest element in each row:

//Largest element in each row

for (row = 0; row < NUMBER_OF_ROWS; row++)

{

largest = matrix[row][0]; //Assume the first element

//of the row is the largest.

for (col = 1; col < NUMBER_OF_COLUMNS; col++)

if (matrix[row][col] > largest)

largest = matrix[row][col];

cout << "The largest element in row " << row + 1

<< " = " << largest << endl;

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

48

Passing Two-Dimensional Arrays as Parameters to Functions

Two-dimensional arrays are passed by reference as parameters to a function

The base address is passed to the formal parameter

Two-dimensional arrays are stored in row order form

When declaring a two-dimensional array as a formal parameter, you can omit the size of the first dimension, but not the second

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

49

Arrays of Strings

Strings in C++ can be manipulated using either the data type string or character arrays (C-strings)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

50

Arrays of Strings and the string Type

The example below declares an array of 100 components of type string:

string list[100];

Basic operations, such as assignment, comparison, and input/output, can be performed on values of the string type

The data in list can be processed just like any one-dimensional array

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

51

Arrays of Strings and C-Strings (Character Arrays)

strcpy(list[1], "Snow White");

FIGURE 8-20 Array list, showing list[1]

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

52

Another Way to Declare a Two-Dimensional Array

Can use typedef to define a two-dimensional array data type:

const int NUMBER_OF_ROWS = 20;

const int NUMBER_OF_COLUMNS = 10;

typedef int tableType[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];

This statement declares an array of 20 rows and 10 columns:

tableType matrix;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

53

Multidimensional Arrays

n-dimensional array: a collection of a fixed number of elements arranged in n dimensions (n >= 1)

Declaration syntax

Code to access a component

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

54

Quick Review (1 of 4)

An array is a structured data type with a fixed number of components of the same type

Components are accessed using their relative positions in the array

Elements of a one-dimensional array are arranged in the form of a list

An array index can be any expression that evaluates to a nonnegative integer

Must always be less than the size of the array

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

55

Quick Review (2 of 4)

The base address of an array is the address of the first array component

When passing an array as an actual parameter, use only its name

Passed by reference only

A function cannot return an array type value

Individual array components can be passed as parameters to functions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

56

Quick Review (3 of 4)

In C++, C-strings are null terminated and are stored in character arrays

Commonly used C-string manipulation functions include: strcpy, strncpy, strcmp, strncmp, and strlen

Parallel arrays hold related information

In a two-dimensional array, the elements are arranged in a table form

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

57

Quick Review (4 of 4)

To access an element of a two-dimensional array, you need a pair of indices: one for row position, one for column position

In row processing, a two-dimensional array is processed one row at a time

In column processing, a two-dimensional array is processed one column at a time

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

58

9781337117562_ppt_ch09.pptx

Chapter 9

Records (structs)

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn about records (structs)

Examine various operations on a struct

Explore ways to manipulate data using a struct

Learn about the relationship between a struct and functions

Examine the difference between arrays and structs

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Discover how arrays are used in a struct

Learn how to create an array of struct items

Learn how to create structs within a structs

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Records (structs) (1 of 3)

struct: a collection of a fixed number of components in which the components are accessed by name

The components may be of different types and are called the members of the struct

Syntax

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Records (structs) (2 of 3)

A struct is a definition, not a declaration

Must declare a variable of that type to use it

struct houseType

{

string style;

int numOfBedrooms;

int numOfBathrooms;

int numOfCarsGarage;

int yearBuilt;

int finishedSquareFootage;

double price;

double tax;

};

//variable declaration

houseType newHouse;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Records (structs) (3 of 3)

FIGURE 9-1 struct newHouse

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Accessing struct Members (1 of 2)

Syntax to access a struct member:

The dot (.) is called the member access operator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Accessing struct Members (2 of 2)

To initialize the members of newStudent:

newStudent.GPA = 0.0;

newStudent.firstName = "John";

newStudent.lastName = "Brown";

FIGURE 9-2 struct newStudent

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Assignment (1 of 2)

Value of one struct variable can be assigned to another struct variable of the same type using an assignment statement

The statement:

student = newStudent;

copies the contents of newStudent into student

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Assignment (2 of 2)

The assignment statement:

student = newStudent;

is equivalent to the following statements:

student.firstName = newStudent.firstName;

student.lastName = newStudent.lastName;

student.courseGrade = newStudent.courseGrade;

student.testScore = newStudent.testScore;

student.programmingScore = newStudent.programmingScore;

student.GPA = newStudent.GPA;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Comparison (Relational Operators)

Compare struct variables member-wise

No aggregate relational operations are allowed

To compare the values of student and newStudent:

if (student.firstName == newStudent.firstName &&

student.lastName == newStudent.lastName)

.

.

.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Input/Output

No aggregate input/output operations are allowed on a struct variable

Data in a struct variable must be read or written one member at a time

The following code would output newStudent contents:

cout << newStudent.firstName << " " << newStudent.lastName

<< " " << newStudent.courseGrade

<< " " << newStudent.testScore

<< " " << newStudent.programmingScore

<< " " << newStudent.GPA << endl;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

struct Variables and Functions

A struct variable can be passed as a parameter by value or by reference

A function can return a value of type struct

The following function displays the contents a struct variable of type studentType:

void printStudent(studentType student)

{

cout << student.firstName << " " << student.lastName

<< " " << student.courseGrade

<< " " << student.testScore

<< " " << student.programmingScore

<< " " << student.GPA << endl;

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Arrays versus structs

TABLE 9-1 Arrays vs. structs

Data Type Array struct
Arithmetic No No
Assignment No Yes
Input/output No (except strings) No
Comparison No No
Parameter passing By reference only By value or by reference
Function returning a value No Yes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Arrays in structs (1 of 3)

Two items are associated with a list:

Values (elements)

Length of the list

Define a struct containing both items:

const int ARRAY_SIZE = 1000;

struct listType

{

int listElem[ARRAY_SIZE]; //array containing the list

int listLength; //length of the list

};

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Arrays in structs (2 of 3)

FIGURE 9-5 struct variable intList

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Arrays in structs (3 of 3)

Consider these statements and refer to the figure below showing the results following execution of the statements:

intList.listLength = 0; //Line 1

intList.listElem[0] = 12; //Line 2

intList.listLength++; //Line 3

intList.listElem[1] = 37; //Line 4

intList.listLength++; //Line 5

FIGURE 9-6 intList after the statements in Lines 1 through 5 execute

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

structs in Arrays (1 of 2)

Example

struct employeeType

{

string firstName;

string lastName;

int personID;

string deptID;

double yearlySalary;

double monthlySalary

double yearToDatePaid;

double monthlyBonus;

};

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

structs in Arrays (2 of 2)

employeeType employees[50]

Declares the array employees of 50 components of type employeeType

FIGURE 9-7 Array of employees

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

structs within a struct

FIGURE 9-8 struct variable newEmployee

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Quick Review (1 of 2)

A struct is a collection of a fixed number of components

Components of a struct can be of different types

Called members

Accessed by name

struct is a reserved word

No memory is allocated for a struct

Memory is allocated only when variables are declared

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Quick Review (2 of 2)

In C++, the dot (.) operator is called the member access operator

Used to access members of a struct

The only built-in operations on a struct are the assignment and member access operations

Neither arithmetic nor relational operations are allowed on structs

A struct can be passed by value or reference

A function can return a value of type struct

A struct can be a member of another struct

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

9781337117562_ppt_ch10.pptx

Chapter 10

Classes and Data Abstraction

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn about classes

Learn about private, protected, and public members of a class

Explore how classes are implemented

Become aware of accessor and mutator functions

Examine constructors and destructors

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Learn about the abstract data type (ADT)

Explore how classes are used to implement ADTs

Become aware of the differences between a struct and a class

Learn about information hiding

Explore how information hiding is implemented in C++

Become aware of inline functions of a class

Learn about the static members of a class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Classes (1 of 4)

Object-oriented design (OOD): a problem solving methodology

Object: combines data and the operations on that data in a single unit

Class: a collection of a fixed number of components

Member: a component of a class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Classes (2 of 4)

The general syntax for defining a class:

A class member can be a variable or a function

If a member of a class is a variable

It is declared like any other variable

You cannot initialize a variable when you declare it

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Classes (3 of 4)

If a member of a class is a function

A function prototype declares that member

Function members can (directly) access any member of the class

A class definition defines only a data type

No memory is allocated

Remember the semicolon (;) after the closing brace

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Classes (4 of 4)

Three categories of class members:

private (default)

Member cannot be accessed outside the class

public

Member is accessible outside the class

protected

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Unified Modeling Language Class Diagrams (1 of 2)

Unified Modeling Language (UML) notation: used to graphically describe a class and its members

+: member is public

-: member is private

#: member is protected

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Unified Modeling Language Class Diagrams (2 of 2)

FIGURE 10-1 UML class diagram of the class clockType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Variable (Object) Declaration

Once defined, you can declare variables of that class type

clockType myClock;

clockType yourClock;

A class variable is called a class object or class instance

FIGURE 10-2 Objects myClock and yourClock

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Accessing Class Members

Once an object is declared, it can access the members of the class

The general syntax for an object to access a member of a class:

If an object is declared in the definition of a member function of the class, it can access the public and private members

The dot (.) is the member access operator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Built-in Operations on Classes

Most of C++’s built-in operations do not apply to classes

Arithmetic operators cannot be used on class objects unless the operators are overloaded

Relational operators cannot be used to compare two class objects for equality

Built-in operations that are valid for class objects:

Member access (.)

Assignment (=)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Assignment Operator and Classes

FIGURE 10-3 myClock and yourClock before and after executing the statement myClock = yourClock;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Class Scope (1 of 2)

A class object can be automatic or static

Automatic: created when the declaration is reached and destroyed when the surrounding block is exited

Static: created when the declaration is reached and destroyed when the program terminates

A member of a class has the same scope as a member of a struct

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Class Scope (2 of 2)

A member of the class is local to the class

You access a class member outside the class by using the class object name and the member access operator (.)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Functions and Classes

Objects can be passed as parameters to functions and returned as function values

As parameters to functions:

Class objects can be passed by value or by reference

If an object is passed by value:

Contents of data members of the actual parameter are copied into the corresponding data members of the formal parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Reference Parameters and Class Objects (Variables) (1 of 2)

Passing by value might require a large amount of storage space and a considerable amount of computer time to copy the value of the actual parameter into the formal parameter

If a variable is passed by reference:

The formal parameter receives only the address of the actual parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Reference Parameters and Class Objects (Variables) (2 of 2)

Pass by reference is an efficient way to pass a variable as a parameter

Problem: when passing by reference, the actual parameter changes when the formal parameter changes

Solution: use const in the formal parameter declaration

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Implementation of Member Functions (1 of 4)

Must write the code for functions defined as function prototypes

Prototypes are left in the class to keep the class smaller and to hide the implementation

To access identifiers local to the class, use the scope resolution operator, (::)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Implementation of Member Functions (2 of 4)

FIGURE 10-4 myClock before and after executing the statement myClock.setTime(3, 48, 52);

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Implementation of Member Functions (3 of 4)

FIGURE 10-5 Objects myClock and yourClock

FIGURE 10-6 Object myClock and parameter otherClock

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Implementation of Member Functions (4 of 4)

Once a class is properly defined and implemented, it can be used in a program

A program that uses/manipulates objects of a class is called a client of that class

When you declare objects of the class clockType, each object has its own copy of the member variables (hr, min, and sec)

These variables are called instance variables of the class

Every object has its own copy of the data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Accessor and Mutator Functions

Accessor function: member function that only accesses the value(s) of member variable(s)

Mutator function: member function that modifies the value(s) of member variable(s)

Constant member function

Member function that cannot modify member variables of that class

Member function heading with const at the end

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Order of public and private Members of a Class

C++ has no fixed order in which to declare public and private members

By default, all members of a class are private

Use the member access specifier public to make a member available for public access

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Constructors (1 of 2)

Use constructors to guarantee that member variables of a class are initialized

Two types of constructors

With parameters

Without parameters (default constructor)

Other properties of constructors

Name of a constructor is the same as the name of the class

A constructor has no type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Constructors (2 of 2)

A class can have more than one constructor

Each must have a different formal parameter list

Constructors execute automatically when a class object enters its scope

They cannot be called like other functions

Which constructor executes depends on the types of values passed to the class object when the class object is declared

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Invoking a Constructor

A constructor is automatically executed when a class variable is declared

Because a class may have more than one constructor, you can invoke a specific constructor

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

Invoking the Default Constructor

Syntax to invoke the default constructor is:

The statement:

clockType yourClock;

declares yourClock to be an object of type clockType and the default constructor executes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

Invoking a Constructor with Parameters

The syntax to invoke a constructor with a parameter is:

Number and type of arguments should match the formal parameters (in the order given) of one of the constructors

Otherwise, C++ uses type conversion and looks for the best match

Any ambiguity causes a compile-time error

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

Constructors and Default Parameters

A constructor can have default parameters

Rules for declaring formal parameters are the same as for declaring default formal parameters in a function

Actual parameters are passed according to the same rules for functions

A default constructor is a constructor with no parameters or with all default parameters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Classes and Constructors: A Precaution

If a class has no constructor(s), C++ provides the default constructor

However, the object declared is still uninitialized

If a class includes constructor(s) with parameter(s), but not the default constructor

C++ does not provide the default constructor

Appropriate arguments must be included when the object is declared

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

In-line Initialization of Data Members and the Default Constructor

C++11 standard allows member initialization in class declarations

Called in-line initialization of the data members

When an object is declared without parameters, then the object is initialized with the in-line initialized values

If declared with parameters, then the default values are overridden by the constructor with the parameters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

Arrays of Class Objects (Variables) and Constructors

If you declare an array of class objects, the class should have the default constructor

The default constructor is typically used to initialize each (array) class object

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

Destructors

Destructors are functions without any type

A class can have only one destructor

The destructor has no parameters

The name of a destructor is the tilde character (~) followed by the class name

Example: ~clockType();

The destructor automatically executes when the class object goes out of scope

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

Data Abstract, Classes, and Abstract Data Types

Abstraction

Separating design details from usage

Separating the logical properties from the implementation details

Abstraction also applicable to data

Abstract data type (ADT): a data type that separates the logical properties from the implementation details

Three things associated with an ADT

Type name: the name of the ADT

Domain: the set of values belonging to the ADT

Set of operations on the data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

A struct versus a class (1 of 2)

By default, members of a struct are public

private specifier can be used in a struct to make a member private

By default, the members of a class are private

classes and structs have the same capabilities

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

A struct versus a class (2 of 2)

In C++, the definition of a struct was expanded to include member functions, constructors, and destructors

If all member variables of a class are public and there are no member functions:

Use a struct

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Information Hiding (1 of 3)

Information hiding refers to hiding the details of the operations on the data

The header file (or interface file) contains the specification details

The header file has an extension h

The implementation file contains the definitions of the functions to implement the operations of an object

This file has an extension cpp

In the header file, include function prototypes and comments that briefly describe the functions

Specify preconditions and/or postconditions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Information Hiding (2 of 3)

Implementation file must include the header file via the include statement

In the include statement:

User-defined header files are enclosed in double quotes

System-provided header files are enclosed between angular brackets

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

39

Information Hiding (3 of 3)

Precondition: a statement specifying the condition(s) that must be true before the function is called

Postcondition: a statement specifying what is true after the function call is completed

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Executable Code

To use an object in a program

The program must be able to access the implementation details of the object

IDEs Visual C++ Express (2013 or 2016) and Visual Studio 2015, and C++ Builder put the editor, compiler, and linker into a package

One command (build, rebuild, or make) compiles program and links it with the other necessary files

These systems also manage multiple file programs in the form of a project

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

More Examples of Classes

Various examples of classes and how to use them in a program are presented

Refer to Example 10-8 through Example 10-11

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Inline Functions

An inline function definition is a member function definition given completely in the definition of the class

Saves the overhead of a function invocation

Very short definitions should be defined as inline functions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

static Members of a Class (1 of 2)

Use the keyword static to declare a function or variable of a class as static

A public static function or member of a class can be accessed using the class name and the scope resolution operator

static member variables of a class exist even if no object of that class type exists

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

44

static Members of a Class (2 of 2)

Multiple objects of a class each have their own copy of non-static member variables

All objects of a class share any static member of the class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

45

Quick Review (1 of 3)

A class is a collection of a fixed number of components

Components of a class are called the members of the class

Accessed by name

Classified into one of three categories: private, protected, and public

In C++, class variables are called class objects or class instances or, simply, objects

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

46

Quick Review (2 of 3)

The only built-in operations on classes are assignment and member selection

Constructors guarantee that data members are initialized when an object is declared

A default constructor has no parameters

The destructor automatically executes when a class object goes out of scope

A class can have only one destructor

The destructor has no parameters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

47

Quick Review (3 of 3)

An abstract data type (ADT) is a data type that separates the logical properties from the implementation details

A public static member, function or data, of a class can be accessed using the class name and the scope resolution operator, ::

static member variables of a class exist even when no object of the class type exists

Instance variables are non-static data members

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

48

9781337117562_ppt_ch11.pptx

Chapter 11

Inheritance and Composition

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn about inheritance

Learn about derived and base classes

Explore how to redefine the member functions of a base class

Examine how the constructors of base and derived classes work

Learn how the destructors of base and derived classes work

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Learn how to construct the header file of a derived class

Become aware of stream classes hierarchy

Explore three types of inheritance: public, protected, and private

Learn about composition (aggregation)

Become familiar with the three basic principles of object-oriented design

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Introduction

Two common ways to relate two classes in a meaningful way are:

Inheritance (“is-a” relationship)

Composition or aggregation: (“has-a” relationship)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Inheritance (1 of 5)

Inheritance is an “is-a” relationship

Example: “every employee is a person”

Inheritance allows creation of new classes from existing classes

Derived classes: new classes created from the existing classes

Base class: the original class

A derived class inherits the properties of its base classes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Inheritance (2 of 5)

Inheritance helps reduce software development complexity

Single inheritance: derived class has a single base class

Multiple inheritance: derived class has more than one base class

Public inheritance: all public members of base class are inherited as public members by derived class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Inheritance (3 of 5)

Inheritance can be viewed as a tree-like, or hierarchical, structure between the base class and its derived classes

FIGURE 11-1 Inheritance hierarchy

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Inheritance (4 of 5)

Syntax of a derived class:

memberAccessSpecifier is public, protected, or private (default)

private members of a base class are private to the base class

Derived class cannot directly access them

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Inheritance (5 of 5)

public members of the base class can be inherited as public or private members

The derived class can include additional members (data and/or functions)

The derived class can redefine public member functions of the base class

Applies only to the objects of the derived class

All member variables of the base class are also member variables of the derived class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Redefining (Overriding) Member Functions of the Base Class (1 of 3)

To redefine a public member function:

The corresponding function in the derived class must have the same name, number, and types of parameters

If the derived class overrides a public member function of the base class, then to call the base class function, specify the:

Name of the base class

Scope resolution operator (::)

Function name with appropriate parameter list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Redefining (Overriding) Member Functions of the Base Class (2 of 3)

FIGURE 11-2 UML class diagram of the class rectangleType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Redefining (Overriding) Member Functions of the Base Class (3 of 3)

boxType is derived from rectangleType, and it is a public inheritance

Also overrides the functions print and area

FIGURE 11-3 UML class diagram of the class boxType and the inheritance hierarchy

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Constructors of Derived and Base Classes

A derived class constructor cannot directly access private members of the base class

Can directly initialize only public member variables of the base class

When a derived object is declared, it must execute one of the base class constructors

A call to the base class constructor is specified in the heading of the derived class constructor definition

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Destructors in a Derived Class

Destructors deallocate dynamic memory allocated by the objects of a class

When a derived class object goes out of scope

Automatically invokes its destructor

When the destructor of the derived class executes

Automatically invokes the destructor of the base class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Header File of a Derived Class

To define new classes, create new header files

To create new derived classes, include commands that specify where the base class definitions can be found

Definitions of the member functions can be placed in a separate file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Multiple Inclusions of a Header File

Use the preprocessor command (#include) to include a header file in a program

The preprocessor processes the program before it is compiled

To avoid multiple inclusions of a file in a program, use certain preprocessor commands in the header file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

C++ Stream Classes (1 of 2)

ios is the base class for all stream classes

Contains formatting flags and member functions to access/modify the flag settings

FIGURE 11-6 C11 stream classes hierarchy

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

C++ Stream Classes (2 of 2)

istream and ostream provide operations for data transfer between memory and devices

istream defines the extraction operator (>>) and functions get and ignore

ostream defines the insertion operator (<<) which is used by cout

ifstream and ofstream objects are for file I/O

Header file fstream contains the definitions for these

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Protected Members of a Class

A derived class cannot directly access private members of it base class

To give it direct access, declare that member as protected

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Inheritance as public, protected, or private (1 of 3)

Assume class B is derived from class A with

class B: memberAccessSpecifier A

If memberAccessSpecifier is public:

public members of A are public in B and can be directly accessed in class B

protected members of A are protected in B and can be directly accessed by member functions (and friend functions) of B

private members of A are hidden in B and can be accessed only through public or protected members of A

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Inheritance as public, protected, or private (2 of 3)

If memberAccessSpecifier is protected:

public members of A are protected members of B and can be accessed by the member functions (and friend functions) of B

protected members of A are protected members of B and can be accessed by the member functions (and friend functions) of B

private members of A are hidden in B and can be accessed only through public or protected members of A

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Inheritance as public, protected, or private (3 of 3)

If memberAccessSpecifier is private:

public members of A are private members of B and can be accessed by member functions of B

protected members of A are private members of B and can be accessed by member functions (and friend functions) of B

private members of A are hidden in B and can be accessed only through public or protected members of A

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Composition (Aggregation) (1 of 2)

In composition, one or more member(s) of a class are objects of another class type

Composition (aggregation) is a “has-a” relation

Arguments to the constructor of a member-object are specified in the heading part of the definition of the constructor

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Composition (Aggregation) (2 of 2)

Member-objects of a class are constructed in the order they are declared

Not in the order listed in the constructor’s member initialization list

They are constructed before the containing class objects are constructed

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Object-Oriented Design (OOD) and Object-Oriented Programming (OOP) (1 of 5)

The fundamental principles of object-oriented design (OOD) are:

Encapsulation: combines data and operations on data in a single unit

Inheritance: creates new objects (classes) from existing objects (classes)

Polymorphism: the ability to use the same expression to denote different operations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

OOD and OOP (2 of 5)

In OOD:

Object is a fundamental entity

Debug at the class level

A program is a collection of interacting objects

OOD encourages code reuse

Object-oriented programming (OOP) implements OOD

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

OOD and OOP (3 of 5)

C++ supports OOP through the use of classes

A function name and operators can be overloaded

A polymorphic function or operator has many forms

Example: division with floating point and division with integer operands

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

OOD and OOP (4 of 5)

Templates provide parametric polymorphism

C++ provides virtual functions to implement polymorphism in an inheritance hierarchy

Allows run-time selection of appropriate member functions

Objects are created when class variables are declared

Objects interact with each other via function calls

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

OOD and OOP (5 of 5)

Every object has an internal state and an external state

Private members form the internal state

Public members form the external state

Only the object can manipulate its internal state

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

Identifying Classes, Objects, and Operations (1 of 5)

To find classes, begin with a problem description and identify all nouns and verbs

From the list of nouns choose the classes

From the list of verbs choose the operations

Suppose we want to write a program that calculates and prints the volume and surface area of a cylinder

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Identifying Classes, Objects, and Operations (2 of 5)

State this problem as follows:

Write a program to input the dimensions of a cylinder and calculate and print the surface area and volume

Nouns are bold and verbs are italic

From the list of nouns, one can visualize a cylinder as a class (cylinderType) from which we can create many cylinder objects of various dimensions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

Identifying Classes, Objects, and Operations (3 of 5)

These nouns are characteristics of a cylinder, so they will not be classes:

Dimensions

Surface area

Volume

Next, determine three pieces of information about this class:

Operations that an object can perform

Operations that can be performed on an object

Information that an object must maintain

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

Identifying Classes, Objects, and Operations (4 of 5)

From the verbs, list possible operations that an object of that class can perform, or have performed, on itself

For the cylinderType class:

Input

Calculate

Print

Dimensions of the cylinder represent the class’s data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

Identifying Classes, Objects, and Operations (5 of 5)

Identifying classes via nouns and verbs from problem descriptions is not the only technique possible

There are several other OOD techniques in the literature

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

Quick Review (1 of 4)

Inheritance and composition are meaningful ways to relate two or more classes

Inheritance is an “is-a” relation

Single inheritance: a derived class is derived from one class, called the base class

Multiple inheritance: a derived class is derived from more than one base class

Composition is a “has-a” relation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

Quick Review (2 of 4)

private members of a base class are private to the base class

public members of a base class can be inherited either as public or private

A derived class can redefine function members of a base class

Redefinition applies only to objects of derived class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Quick Review (3 of 4)

A call to a base class constructor (with parameters) is specified in the heading of the definition of the derived class constructor

When initializing object of a derived class, the base class constructor is executed first

In composition (aggregation):

A class member is an object of another class

A call to constructor of member objects is specified in heading of the definition of class’s constructor

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Quick Review (4 of 4)

Three basic principles of OOD:

Encapsulation

Inheritance

Polymorphism

To find classes:

Describe the problem

Choose classes from the list of nouns

Choose operations from the list of verbs

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

9781337117562_ppt_ch12.pptx

Chapter 12

Pointers, Classes, Virtual Functions, Abstract Classes, and Lists

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

Objectives (1 of 3)

In this chapter, you will:

Learn about the pointer data type and pointer variables

Explore how to declare and manipulate pointer variables

Learn about the address of the operator and the dereferencing operator

Learn how pointers work with classes and structs

Discover dynamic variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 3)

Explore how to use the new and delete operators to manipulate dynamic variables

Learn about pointer arithmetic

Learn how to work with dynamic arrays

Become familiar with the limitations of range-based for loops with dynamic arrays

Explore how pointers work with functions as parameters and functions as return values

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Objectives (3 of 3)

Become familiar with the shallow and deep copies of data

Discover the peculiarities of classes with pointer member variables

Learn about virtual functions

Become aware of abstract classes

Learn about array based lists and the basic operations on them

Examine the relationship between the address of operator and classes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Pointer Data Type and Pointer Variables

A pointer variable is a variable whose content is a memory address

No name is associated with the pointer data type in C++

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Declaring Pointer Variables (1 of 2)

The general syntax to declare a pointer variable is:

The statements below each declare a pointer:

int *p;

char *ch;

These statements are equivalent:

int *p;

int* p;

int * p;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Declaring Pointer Variables (2 of 2)

In the statement:

int* p, q;

Only p is a pointer variable

q is an int variable

To avoid confusion, attach the character * to the variable name:

int *p, q;

int *p, *q;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Address of Operator (&)

Address of operator (&):

A unary operator that returns the address of its operand

Example:

int x;

int *p;

p = &x; //Assigns the address of x to p

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Dereferencing Operator (*)

Dereferencing operator (or indirection operator):

When used as a unary operator, * refers to object to which its operand points

Example:

cout << *p << endl;

Prints the value stored in the memory location pointed to by p

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Classes, structs, and Pointer Variables (1 of 3)

You can declare pointers to other data types, such as a struct:

struct studentType

{

char name[26];

double gpa;

int sID;

char grade;

};

studentType student;

studentType* studentPtr;

student is an object of type studentType

studentPtr is a pointer variable of type studentType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Classes, structs, and Pointer Variables (2 of 3)

To store address of student in studentPtr:

studentPtr = &student;

To store 3.9 in component gpa of student:

(*studentPtr).gpa = 3.9;

( ) used because dot operator has higher precedence than dereferencing operator

Alternative: use member access operator arrow (->)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Classes, structs, and Pointer Variables (3 of 3)

Syntax to access a class (struct) member using the operator -> :

Thus,

(*studentPtr).gpa = 3.9;

is equivalent to:

studentPtr->gpa = 3.9;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Initializing Pointer Variables

C++ does not automatically initialize variables

Pointer variables must be initialized if you do not want them to point to anything

Initialized to the value 0 using the null pointer

Or, use the NULL named constant

The number 0 is the only number that can be directly assigned to a pointer variable

C++11 Standard includes a nullptr

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Dynamic Variables

Dynamic variables are created during execution

C++ creates dynamic variables using pointers

new and delete operators: used to create and destroy dynamic variables

new and delete are reserved words in C++

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Operator new (1 of 2)

new has two forms:

intExp is any expression evaluating to a positive integer

new allocates memory (a variable) of the designated type and returns a pointer to it

The allocated memory is uninitialized

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Operator new (2 of 2)

Example: p = new int;

Creates a variable during program execution somewhere in memory

Stores the address of the allocated memory in p

To access allocated memory, use *p

A dynamic variable cannot be accessed directly

Because it is unnamed

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Operator delete

Memory leak: previously allocated memory that cannot be reallocated

To avoid a memory leak, when a dynamic variable is no longer needed, destroy it to deallocate its memory

delete operator: used to destroy dynamic variables

Syntax:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Operations on Pointer Variables (1 of 2)

Assignment: value of one pointer variable can be assigned to another pointer of same type

Relational operations: two pointer variables of same type can be compared for equality, etc.

Some limited arithmetic operations

Integer values can be added and subtracted from a pointer variable

Value of one pointer variable can be subtracted from another pointer variable

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Operations on Pointer Variables (2 of 2)

Pointer arithmetic can be very dangerous:

Program can accidentally access memory locations of other variables and change their content without warning

Some systems might terminate the program with an appropriate error message

Always exercise extra care when doing pointer arithmetic

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Dynamic Arrays (1 of 2)

Dynamic array: array created during program execution

Example:

int *p;

p = new int[10];

*p = 25; //stores 25 in the first memory location

p++; //to point to next array component

*p = 35; // stores 35 into the second memory location

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Dynamic Arrays (2 of 2)

Can use array notation to access these memory locations

Example:

p[0] = 25;

p[1] = 35;

Stores 25 and 35 into the first and second array components, respectively

An array name is a constant pointer

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Functions and Pointers

Pointer variable can be passed as a parameter either by value or by reference

As a reference parameter in a function heading, use &:

void pointerParameters(int* &p, double *q)

{

. . .

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Pointers and Function Return Values

A function can return a value of type pointer:

int* testExp(...)

{

. . .

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Dynamic Two-Dimensional Arrays

You can create dynamic multidimensional arrays

Examples:

int *board[4]; //declares board to be an array of four

//pointers wherein each pointer is of type

for (int row = 0; row < 4; row++)

board[row] = new int[6]; //creates the rows of board

int **board; //declares board to be a pointer to a pointer

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Shallow versus Deep Copy and Pointers

Shallow copy: when two or more pointers of the same types point to the same memory

They point to the same data

Danger: deleting one deletes the data pointed to by all of them

Deep copy: when the contents of the memory pointed to by a pointer are copied to the memory location of another pointer

Two copies of the data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Classes and Pointers: Some Peculiarities (1 of 2)

Example class:

class ptrMemberVarType

{

public:

.

.

.

private:

int x;

int lenP;

int *p;

};

Example program statements:

ptrMemberVarType objectOne;

ptrMemberVarType objectTwo;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Classes and Pointers: Some Peculiarities (2 of 2)

FIGURE 12-13 Objects objectOne and objectTwo

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Destructor

If objectOne goes out of scope, its member variables are destroyed

Memory space of a dynamic array stays marked as allocated, even though it cannot be accessed

Solution: in destructor, ensure that when objectOne goes out of scope, its array memory is deallocated:

ptrMemberVarType::~ptrMemberVarType()

{

delete [] p;

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

Assignment Operator

After a shallow copy: if objectTwo.p deallocates memory space to which it points, objectOne.p becomes invalid

FIGURE 12-15 Objects objectOne and objectTwo

Solution: extend definition of the assignment operator to avoid shallow copying of data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

Copy Constructor (1 of 3)

Default member-wise initialization:

Initializing a class object by using the value of an existing object of the same type

Example:

ptrMemberVarType objectThree(objectOne);

Copy constructor: provided by the compiler

Performs this initialization

Leads to a shallow copying of the data if class has pointer member variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Copy Constructor (2 of 3)

Similar problem occurs when passing objects by value

Copy constructor automatically executes in three situations:

When an object is declared and initialized by using the value of another object

When an object is passed by value as a parameter

When the return value of a function is an object

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

Copy Constructor (3 of 3)

Solution: override the copy constructor

For classes with pointer member variables, three things are normally done:

Include the destructor in the class

Overload the assignment operator for the class

Include the copy constructor

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

Inheritance, Pointers, and Virtual Functions (1 of 3)

Can pass an object of a derived class to a formal parameter of the base class type

Compile-time binding: the necessary code to call specific function is generated by compiler

Also known as static binding or early binding

Virtual function: binding occurs at program execution time, not at compile time

Declared with reserved word virtual

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

Inheritance, Pointers, and Virtual Functions (2 of 3)

Run-time binding:

Compiler does not generate code to call a specific function: it generates information to enable run-time system to generate specific code for the function call

Also known as late binding or dynamic binding

Note: cannot pass an object of base class type to a formal parameter of the derived class type

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

Inheritance, Pointers, and Virtual Functions (3 of 3)

Values of a derived class object can be copied into a base class object

Slicing problem: if derived class has more data members than base class, some data could be lost

Solution: use pointers for both base and derived class objects

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

Classes and Virtual Destructors (1 of 2)

Classes with pointer member variables should have the destructor

Destructor should deallocate storage for dynamic objects

If a derived class object is passed to a formal parameter of the base class type, destructor of the base class executes

Regardless of whether object is passed by reference or by value

Solution: use a virtual destructor (base class)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Classes and Virtual Destructors (2 of 2)

Virtual destructor of a base class automatically makes the destructor of a derived class virtual

After executing the destructor of the derived class, the destructor of the base class executes

If a base class contains virtual functions, make the destructor of the base class virtual

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Abstract Classes and Pure Virtual Functions (1 of 2)

New classes can be derived through inheritance without designing them from scratch

Derived classes:

Inherit existing members of base class

Can add their own members

Can redefine or override public and protected member functions

Base class can contain functions that you would want each derived class to implement

However, base class may contain functions that may not have meaningful definitions in the base class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Abstract Classes and Pure Virtual Functions (2 of 2)

Pure virtual functions do not have definitions (bodies have no code)

Example:

virtual void draw() = 0;

An abstract class is a class with one or more virtual functions

It can contain instance variables, constructors, and functions that are not pure virtual

It must provide the definitions of the constructor and functions that are not pure virtual

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

39

Array-Based Lists (1 of 3)

List is a collection of elements of the same type

Common set of list operations

1. Create the list. The list is initialized to an empty state.

2. Determine whether the list is empty.

3. Determine whether the list is full.

4. Find the size of the list.

5. Destroy, or clear, the list.

6. Determine whether an item is the same as a given list element.

7. Insert an item in the list at the specified location.

8. Remove an item from the list at the specified location.

9. Replace an item at the specified location with another item.

10. Retrieve an item from the list at the specified location.

11. Search the list for a given item.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Array-Based Lists (2 of 3)

FIGURE 12-22 UML diagram for the class arrayListType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Array-Based Lists (3 of 3)

Lists can be unordered or ordered

Either type can be derived from abstract class arrayListType

Ordered list includes function insert to insert an item in its proper place

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 12-23 Array list

‹#›

42

Address of Operator and Classes (1 of 2)

& operator can create aliases to an object

Example:

int x;

int &y = x; //x and y refer to the same memory location

//y is like a constant pointer variable

y = 25; //sets the value of y (and of x) to 25

x = 2 * x + 30; //updates value of x and y

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

43

Address of Operator and Classes (2 of 2)

Address of operator can also be used to return the address of a private member variable of a class

However, if you are not careful, this operation can result in serious errors in the program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

44

Quick Review (1 of 2)

Pointer variables contain the addresses of other variables as their values

Declare a pointer variable with an asterisk, *, between the data type and the variable

Address of operator (&) returns the address of its operand

Unary operator * is the dereferencing operator

Member access operator (->) accesses the object component pointed to by a pointer

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

45

Quick Review (2 of 2)

Dynamic variable: created during execution

Created using new

Deallocated using delete

Shallow copy: two or more pointers of the same type point to the same memory

Deep copy: two or more pointers of the same type have their own copies of the data

Binding of virtual functions occurs at execution time (dynamic or run-time binding)

A list is a collection of elements of the same type. Can be ordered or unordered

Common set of list operations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

46

9781337117562_ppt_ch13.pptx

Chapter 13

Overloading and Templates

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

Objectives (1 of 2)

In this chapter, you will:

Learn about overloading

Become familiar with the restrictions on operator overloading

Examine the pointer this

Learn about friend functions

Learn how to overload operators as members and nonmembers of a class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Discover how to overload various operators

Become familiar with the requirements for classes with pointer member variables

Learn about templates

Explore how to construct function templates and class templates

Become aware of C++11 random number generators

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Introduction

Templates enable you to write generic code for related functions and classes

Function templates simplify function overloading

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Why Operator Overloading Is Needed (1 of 2)

Consider the following statements:

clockType myClock(8, 23, 34);

clockType yourClock(4, 5, 30);

Which version of C++ statements would you prefer?

myClock.printTime();

myClock.incrementSeconds();

if (myClock.equalTime(yourClock))

.

.

.

cout << myClock;

myClock++;

if (myClock == yourClock)

.

.

.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Why Operator Overloading Is Needed (2 of 2)

Assignment and member selection are the only built-in operations on classes

Other operators cannot be applied directly to class objects

Operator overloading extends the definition of an operator to work with a user-defined data type

C++ allows you to extend the definitions of most of the operators to work with classes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Operator Overloading

Most existing C++ operators can be overloaded to manipulate class objects

New operators cannot be created

An operator function is a function that overloads an operator

Use reserved word operator followed by the operator as the function name

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Syntax for Operator Functions

Syntax of an operator function heading:

It is a value-returning function

operator is a reserved word

To overload an operator for a class:

Include the operator function declaration in the class definition

Write the definition of the operator function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Overloading an Operator: Some Restrictions

Cannot change the precedence of an operator

Associativity cannot be changed

Default parameters cannot be used

Cannot change number of parameters

Cannot create new operators

Cannot overload: . .* :: ?: sizeof

How the operator works with built-in types remains the same

Can overload for user-defined objects or for a combination of user-defined and built-in objects

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Pointer this

Every object of a class maintains a (hidden) pointer to itself called this

When an object invokes a member function

this is referenced by the member function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Friend Functions of Classes

A friend function (of a class) is a nonmember function of the class that has access to all the members of the class

Use the reserved word friend in the function prototype in the class definition

Friendship is always given by the class

class classIllusFriend

{

friend void two(/*parameters*/);

.

.

.

};

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Definition of a friend Function

friend does not appear in the heading of the function’s definition

When writing the friend function’s definition

The name of the class and the scope resolution operator are not used

void two(/*parameters*/)

{

.

.

.

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Operator Functions as Member and Nonmember Functions

To overload (), [], ->, or = for a class, the function must be a member of the class

Suppose op is overloaded for opOverClass:

If the leftmost operand of op is an object of a different type, the overloading function must be a nonmember (friend) of the class

If the overloading function for op is a member of opOverClass, then when applying op on objects of type opOverClass, the leftmost operand must be of type opOverClass

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Overloading Binary Operators

If # represents a binary operator (e.g., + or ==) that is to be overloaded for rectangleType

It can be overloaded as either a member function of the class or as a friend function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Overloading the Binary Operators as Member Functions

Function prototype (included in the class definition):

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Overloading the Binary Operators (Arithmetic or Relational) as Nonmember Functions

Function prototype (included in class definition):

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Overloading the Stream Insertion (<<) and Extraction (>>) Operators

Consider the expression:

cout << myRectangle;

Leftmost operand is an ostream object, not a rectangleType object

Thus, the operator function that overloads << for rectangleType must be a nonmember function of the class

The same applies to the function that overloads >>

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Overloading the Stream Insertion Operator (<<)

Function prototype:

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Overloading the Stream Extraction Operator (>>)

Function prototype:

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Overloading the Assignment Operator (=)

Function prototype:

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Overloading Unary Operators

To overload a unary operator for a class:

If the operator function is a member of the class, it has no parameters

If the operator function is a nonmember (i.e., a friend function), it has one parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Overloading the Increment (++) and Decrement (--) Operators (1 of 4)

General syntax to overload the pre-increment operator ++ as a member function

Function prototype:

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Overloading the Increment (++) and Decrement (--) Operators (2 of 4)

General syntax to overload the pre-increment operator ++ as a nonmember function

Function prototype:

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Overloading the Increment (++) and Decrement (--) Operators (3 of 4)

General syntax to overload the post-increment operator ++ as a member function:

Function prototype:

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Overloading the Increment (++) and Decrement (--) Operators (4 of 4)

General syntax to overload the post-increment operator ++ as a nonmember function:

Function prototype:

Function definition:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Operator Overloading: Member versus Nonmember (1 of 2)

Some operators must be overloaded as member functions and some must be overloaded as nonmember (friend) functions

Binary arithmetic operator + can be overloaded either way

As a member function, operator + has direct access to data members of one of the objects

Need to pass only one object as a parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Operator Overloading: Member versus Nonmember (2 of 2)

Overload + as a nonmember function

Must pass both objects as parameters

Code may be somewhat clearer this way

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

Classes and Pointer Member Variables (Revisited)

Recall that the assignment operator copies member variables from one object to another of the same type

Does not work well with pointer member variables

Classes with pointer member variables must:

Explicitly overload the assignment operator

Include the copy constructor

Include the destructor

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

Operator Overloading: One Final Word

If an operator op is overloaded for a class, e.g., rectangleType

When you use op on objects of type rectangleType, the body of the function that overloads the operator op for the class rectangleType executes

Therefore, whatever code you put in the body of the function executes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

Overloading the Array Index (Subscript) Operator ([])

Syntax to declare operator[] as a member of a class for nonconstant arrays:

Syntax to declare operator[] as a member of a class for constant arrays:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Function Overloading

Overloading a function refers to having several functions with the same name, but different parameters

The parameter list determines which function will execute

Must provide the definition of each function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

Templates (1 of 2)

Template: a single code body for a set of related functions (function template) and related classes (class template)

Syntax:

Type is the data type

declaration is either a function declaration or a class declaration

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

Templates (2 of 2)

class in the heading refers to any user-defined type or built-in type

Type is a formal parameter to the template

Just as variables are parameters to functions, data types are parameters to templates

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

Function Templates

Syntax of the function template:

Type is a formal parameter of the template used to:

Specify type of parameters to the function

Specify return type of the function

Declare variables within the function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

Class Templates

Class template: a single code segment for a set of related classes

Called parameterized types

Syntax:

A template instantiation can be created with either a built-in or user-defined type

The function members of a class template are considered to be function templates

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

Header File and Implementation File of a Class Template (1 of 2)

Passing a parameter to a function takes effect at run time

Passing a parameter to a class template takes effect at compile time

Cannot compile the implementation file independently of the client code

Can put class definition and definitions of the function templates directly in the client code

Can put class definition and the definitions of the function templates in the same header file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Header File and Implementation File of a Class Template (2 of 2)

Another alternative is to put class definition and function definitions in separate files

Include directive to the implementation file at the end of the header file

In either case, function definitions and client code are compiled together

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Array-Based Lists (Revisited)

Using class templates allows creation of generic code

Can create abstract class arrayListType as an ADT

Must overload the assignment operator

Can derive unorderedArrayListType or orderedArrayListType from arrayListType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

C++11 Random Number Generator

To use C++ 11 random number generator functions we use an engine and a distributor

An engine returns unpredictable (random) bits

A distribution returns random numbers whose likelihoods correspond to a specific shape such as a uniform or normal distribution

The C++11 standard library provides 25 distribution types in five categories

uniform_int_distribution and uniform_real_distribution fall in the category of uniform distributions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Quick Review (1 of 3)

An operator that has different meanings with different data types is said to be overloaded

Operator function: a function that overloads an operator

operator is a reserved word

Operator functions are value-returning

Operator overloading provides the same concise notation for user-defined data types as for built-in data types

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Quick Review (2 of 3)

Only existing operators can be overloaded

The pointer this refers to the object

A friend function is a nonmember of a class

If an operator function is a member of a class

The leftmost operand of the operator must be a class object (or a reference to a class object) of that operator’s class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

Quick Review (3 of 3)

Classes with pointer variables must overload the assignment operator, and include both the copy constructor and the destructor

In C++, template is a reserved word

Function template: a single code segment for a set of related functions

Class template: a single code segment for a set of related classes

Are called parameterized types

C++11 provides many functions to implement random number generator.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

42

9781337117562_ppt_ch14.pptx

Chapter 14

Exception Handling

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

Objectives (1 of 2)

In this chapter, you will:

Learn what an exception is

Learn how to handle exceptions within a program

Learn how a try/catch block is used to handle exceptions

Learn how to throw an exception

Become familiar with C++ exception classes and how to use them in a program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Learn how to create your own exception classes

Discover how to throw and rethrow an exception

Explore exception handling techniques

Explore stack unwinding

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Introduction

An exception is an undesirable event detectable during program execution

Code to handle exceptions depends on the type of application being developed

May or may not want the program to terminate when an exception occurs

Can add exception-handling code at point where an error can occur

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Handling Exceptions Within a Program

assert function:

Checks if an expression meets certain condition(s)

If conditions are not met, it terminates the program

Example: division by 0

If divisor is zero, assert terminates the program with an error message

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

C++ Mechanisms of Exception Handling

try/catch block: used to handle exceptions

Exception must be thrown in a try block and caught by a catch block

C++ provides support to handle exceptions via a hierarchy of classes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

try/catch Block (1 of 5)

Statements that may generate an exception are placed in a try block

The try block also contains statements that should not be executed if an exception occurs

try block is followed by one or more catch blocks

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

try/catch Block (2 of 5)

General syntax of the try/catch block

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

try/catch Block (3 of 5)

catch block:

Specifies the type of exception it can catch

Contains an exception handler

If the heading of a catch block contains ... (ellipses) in place of parameters:

Block can catch exceptions of all types

If no exception is thrown in a try block:

All catch blocks are ignored

Execution resumes after the last catch block

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

try/catch Block (4 of 5)

If an exception is thrown in a try block:

Remaining statements (in block) are ignored

Program searches catch blocks in order, looking for an appropriate exception handler

If the type of thrown exception matches the parameter type in one of the catch blocks:

Code of that catch block executes

Remaining catch blocks are ignored

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

try/catch Block (5 of 5)

A catch block can have at most one catch block parameter

catch block parameter becomes a placeholder for the value thrown

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Throwing an Exception

For try/catch to work, the exception must be thrown in the try block

General syntax:

where expression is a constant value, variable, or object

Object being thrown can be a specific object or an anonymous object

In C++, an exception is a value

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Order of catch Blocks

catch block can catch:

All exceptions of a specific type

All types of exceptions

A catch block with an ellipsis (...) catches any type of exception

If used, it should be the last catch block of that sequence

Be careful about the order in which you list catch blocks

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Using C++ Exception Classes (1 of 2)

C++ provides support to handle exceptions via a hierarchy of classes

The class exception is the base class of the exception classes provided by C++

Function what

Contained in class exception

Returns a string containing an appropriate message

All derived classes of the class exception override the function what to issue their own error messages

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Using C++ Exception Classes (2 of 2)

Two subclasses of exception (defined in stdexcept):

logic_error includes subclasses:

invalid_argument: for use when illegal arguments are used in a function call

out_of_range: string subscript out of range error

length_error: if a length greater than the maximum allowed for a string object is used

runtime_error includes subclasses:

overflow_error and underflow_error

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Creating Your Own Exception Classes (1 of 2)

Can create your own exception classes to handle specific exceptions

C++ uses the same mechanism to process these exceptions

throw statement: used to throw your own exceptions

Any class can be an exception class

How you use the class makes it an exception class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Creating Your Own Exception Classes (2 of 2)

Exception class with member variables typically includes:

Constructors

The function what

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Rethrowing and Throwing an Exception (1 of 3)

When an exception occurs in a try block, control immediately passes to one of the catch blocks, which either:

Handles the exception, or partially processes the exception, then rethrows the same exception

Rethrows another exception for the calling environment to handle

This allows you to provide exception-handling code all in one place

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Rethrowing and Throwing an Exception (2 of 3)

Syntax to rethrow an exception caught by a catch block:

If the same exception is to be rethrown:

If a different exception is to be thrown

where expression is a constant value, variable, or object

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Rethrowing and Throwing an Exception (3 of 3)

Object being thrown can be:

A specific object

An anonymous object

A function specifies the exceptions it throws in its heading using the throw clause

Example:

void expThrowExcep(int x) throw (int, string, divisionByZero)

{

.

.

.

//include the appropriate throw statements

.

.

.

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Exception-Handling Techniques

When an exception occurs, the programmer usually has three choices:

Terminate the program

Include code to recover from the exception

Log the error and continue

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Terminate the Program

In some cases, it is best to terminate the program when an exception occurs

Example: if an input file does not exist when the program executes

There is no point in continuing with the program

Program can output an appropriate error message and terminate

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Fix the Error and Continue

In some cases, you will want to handle the exception and let the program continue

Example: a user inputs a letter instead of a number

The input stream will enter the fail state

Can include the necessary code to keep prompting the user to input a number until the entry is valid

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Log the Error and Continue

Example: if the program is designed to run a nuclear reactor or continuously monitor a satellite

It cannot be terminated if an exception occurs

When an exception occurs:

The program should write the exception into a file and continue to run

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Stack Unwinding (1 of 2)

When an exception is thrown in a function, the function can do the following:

Do nothing

Partially process the exception and throw the same exception or a new exception

Throw a new exception

In each case, the function-call stack is unwound so that the exception can be caught in the next try/catch block

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Stack Unwinding (2 of 2)

When the function call stack is unwound:

The function in which the exception was not caught and/or rethrown terminates

Memory for its local variables is destroyed

Stack unwinding continues until:

A try/catch handles the exception, or

The program does not handle the exception

The function terminate is called to terminate the program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Quick Review (1 of 3)

An exception is an undesirable event detectable during program execution

assert checks whether an expression meets a specified condition; terminates if not met

try/catch block handles exceptions

Statements that may generate an exception are placed in a try block

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

Quick Review (2 of 3)

A catch block specifies type of exception it can catch and contains an exception handler

If no exceptions are thrown in a try block, all catch blocks for that try block are ignored

Data type of catch block parameter specifies type of exception that catch block can catch

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

Quick Review (3 of 3)

exception is the base class for exception classes

what function returns a string containing the exception object thrown by built-in exception classes

You can create your own exception classes

A function specifies the exceptions it throws in its heading with the throw clause

If the program does not handle the exception, then the function terminate terminates the program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

9781337117562_ppt_ch15.pptx

Chapter 15

Recursion

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

Objectives (1 of 2)

In this chapter, you will:

Learn about recursive definitions

Explore the base case and the general case of a recursive definition

Discover what a recursive algorithm is

Learn about recursive functions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Become familiar with direct and indirect recursion

Explore how to use recursive functions to implement recursive algorithms

Become aware of recursion vs. iteration

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Recursive Definitions (1 of 5)

Recursion: solving a problem by reducing it to smaller versions of itself

Provides a powerful way to solve certain problems which would be complicated otherwise

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Recursive Definitions (2 of 5)

Recursive definition: a definition in which something is defined in terms of a smaller version of itself

Base case: the case for which the solution is obtained directly

Every recursive definition must have one (or more) base case(s)

The general case must eventually reduce to a base case

The base case stops the recursion

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Recursive Definitions (3 of 5)

Example: factorial of a nonnegative integer

0! = 1 (15-1)

n! = n x (n – 1)! if n > 0 (15-2)

Equation 15-1 is called the base case

Equation 15-2 is called the general case

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Recursive Definitions (4 of 5)

A recursive algorithm finds a solution to a given problem by reducing the problem to smaller versions of itself

Must have one (or more) base cases

General solution must eventually reduce to a base case

A recursive function is a function that calls itself

Recursive algorithms are implemented using recursive functions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Recursive Definitions (5 of 5)

Think of a recursive function as having infinitely many copies of itself

Every call has its own code and its own set of parameters and local variables

After completing a particular recursive call:

Control goes back to the calling environment, the previous call

Execution begins from the point immediately following the recursive call

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Direct and Indirect Recursion

Directly recursive: a function that calls itself

Indirectly recursive: a function that calls another function and eventually results in the original function call

Tail recursive function: a recursive function in which the last statement executed is the recursive call

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Infinite Recursion (1 of 2)

Infinite recursion: every recursive call results in another recursive call

In theory, infinite recursion executes forever

Because computer memory is finite:

Function executes until the system runs out of memory

Results in an abnormal program termination

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Infinite Recursion (2 of 2)

To design a recursive function:

Understand the problem requirements

Determine limiting conditions

Identify the base cases and provide a direct solution to each base case

Identify the general cases and provide a solution to each general case in terms of smaller versions of itself

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Recursion or Iteration? (1 of 4)

An iterative control structure uses a loop to repeat a set of statements

There are usually two ways to solve a particular problem

Iteration (looping)

Recursion

When choosing the method of solving, we must consider:

The nature of the problem

Efficiency

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Recursion or Iteration? (2 of 4)

Whenever a function is called:

Memory space for its formal parameters and (automatic) local variables is allocated

When the function terminates:

That memory space is then deallocated

Every (recursive) call has its own set of parameters and (automatic) local variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Recursion or Iteration? (3 of 4)

Overhead associated with executing a (recursive) function in terms of:

Memory space

Computer time

A recursive function executes more slowly than its iterative counterpart

Today’s computers are fast

Overhead of a recursion function is not noticeable

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Recursion or Iteration? (4 of 4)

Sometimes an iterative solution is more obvious and easier to understand

If the definition of a problem is inherently recursive, consider a recursive solution

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Quick Review (1 of 3)

Recursion: process of solving a problem by reducing it to smaller versions of itself

Recursive definition: defines a problem in terms of smaller versions of itself

Has one or more base cases

Recursive algorithm: solves a problem by reducing it to smaller versions of itself

Has one or more base cases

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Quick Review (2 of 3)

The solution to the problem in a base case is obtained directly

A recursive function is a function that calls itself

Must have one or more base cases

Recursive algorithms are implemented using recursive functions

The general solution breaks the problem into smaller versions of itself

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Quick Review (3 of 3)

The general case must eventually be reduced to a base case

The base case stops the recursion

A function is called directly recursive if it calls itself

A function that calls another function and eventually results in the original function call is said to be indirectly recursive

A recursive function in which the last statement executed is the recursive call is called a tail recursive function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

9781337117562_ppt_ch16.pptx

Chapter 16

Linked Lists

C++ Programming: From Problem Analysis to Program Design, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn about linked lists

Become familiar with the basic properties of linked lists

Explore the insertion and deletion operations on linked lists

Discover how to build and manipulate a linked list

Learn how to implement linked lists as ADTs

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

2

Objectives (2 of 2)

Learn how to create linked list iterators

Learn how to implement the basic operations on a linked list

Learn how to create unordered linked lists

Learn how to create ordered linked lists

Learn how to construct a

Become familiar with circular linked lists doubly linked list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

3

Introduction

Data can be organized and processed sequentially using an array, called a sequential list

Problems with an array

Array size is fixed

Unsorted array: searching for an item is slow

Sorted array: insertion and deletion is slow because it requires data movement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

4

Linked Lists (1 of 3)

Linked list: a collection of items (nodes) containing two components:

Data

Address (link) of the next node in the list

FIGURE 16-1 Structure of a node

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

5

Linked Lists (2 of 3)

FIGURE 16-2 Linked list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

6

Linked Lists (3 of 3)

A node is declared as a class or struct

Data type of a node depends on the specific application

Link component of each node is a pointer

Variable declaration:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

7

Linked Lists: Some Properties (1 of 3)

Example: linked list with four nodes (Figure 16-4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

8

Linked Lists: Some Properties (2 of 3)

current = head;

Copies value of head into current

FIGURE 16-5 Linked list after the statement current = head; executes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

9

Linked Lists: Some Properties (3 of 3)

current = current->link;

FIGURE 16-6 List after the statement current = current->link; executes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

10

Traversing a Linked List (1 of 2)

Basic operations of a linked list:

Search for an item in the list

Insert an item in the list

Delete an item from the list

Traversal: given a pointer to the first node of the list, step through the nodes of the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

11

Traversing a Linked List (2 of 2)

To traverse a linked list:

Example:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

current = head;

while (current != nullptr)

{

//Process the current node

current = current->link;

}

current = head;

while (current != nullptr)

{

cout << current->info << " ";

current = current->link;

}

‹#›

12

Item Insertion and Deletion

Definition of a node:

Variable declaration:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

13

Insertion (1 of 4)

To insert a new node with info 50 after p in this list:

FIGURE 16-7 Linked list before item insertion

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

14

Insertion (2 of 4)

TABLE 16-1 Inserting a Node in a Linked List

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

15

Insertion (3 of 4)

Can use two pointers to simplify the insertion code somewhat:

FIGURE 16-9 List with pointers p and q

To insert newNode between p and q:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

16

Insertion (4 of 4)

TABLE 16-2 Inserting a Node in a Linked List Using Two Pointers

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

17

Deletion (1 of 3)

Node with info 34 is to be deleted:

FIGURE 16-10 Node to be deleted is with info 34

FIGURE 16-11 List after the statement newNode->link = q; executes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

18

Deletion (2 of 3)

Node with info 34 is removed from the list, but memory is still occupied

Node is dangling

Must keep a pointer to the node to be able to deallocate its memory

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

19

Deletion (3 of 3)

TABLE 16-3 Deleting a Node from a Linked List

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

20

Building a Linked List

If data is unsorted, the list will be unsorted

Can build a linked list forward or backward

Forward: a new node is always inserted at the end of the linked list

Backward: a new node is always inserted at the beginning of the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

21

Building a Linked List Forward (1 of 4)

Need three pointers to build the list:

One to point to the first node in the list, which cannot be moved

One to point to the last node in the list

One to create the new node

Example:

Data: 2 15 8 24 34

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

22

Building a Linked List Forward (2 of 4)

FIGURE 16-12 Empty list

FIGURE 16-14 List after inserting newNode in it

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

23

Building a Linked List Forward (3 of 4)

FIGURE 16-15 List and newNode with info 15

FIGURE 16-16 List after inserting newNode at the end

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

24

Building a Linked List Forward (4 of 4)

Now repeat this process three more times:

FIGURE 16-17 List after inserting 8, 24, and 34

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

25

Building a Linked List Backward

Algorithm to build a linked list backward:

Initialize first to nullptr

For each item in the list

Create the new node, newNode

Store the data in newNode

Insert newNode before first

Update the value of the pointer first

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

26

Linked List as an ADT (1 of 4)

Basic operations on linked lists:

Initialize the list

Determine whether the list is empty

Print the list

Find the length of the list

Destroy the list

Retrieve info contained in the first or last node

Search the list for a given item

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

27

Linked List as an ADT (2 of 4)

Basic operations on linked lists (cont’d.):

Insert an item in the list

Delete an item from the list

Make a copy of the linked list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

28

Linked List as an ADT (3 of 4)

Two general types of linked lists:

Sorted and unsorted lists

Algorithms to implement the operations search, insert, and remove differ slightly for sorted and unsorted lists

abstract class linkedListType will implement basic linked list operations

Derived classes: unorderedLinkedList and orderedLinkedList

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

29

Linked List as an ADT (4 of 4)

For an unordered linked list, can insert a new item at either the end or the beginning

buildListForward inserts item at the end

buildListBackward inserts item at beginning

Will need two functions:

insertFirst and insertLast

Will use two pointers in the list:

first and last

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

30

Structure of Linked List Nodes

Each node has two member variables

We implement the node of a linked list as a struct

Definition of the struct nodeType:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

31

Member Variables of the class linkedListType

linkedListType has three member variables:

Two pointers: first and last

count: the number of nodes in the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

32

Linked List Iterators (1 of 4)

To process each node of the list

List must be traversed, starting at first node

Iterator: object that produces each element of a container, one element at a time

The two most common iterator operations:

++ (the increment operator)

* (the dereferencing operator)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

33

Linked List Iterators (2 of 4)

An iterator is an object

Need to define a class (linkedListIterator) to create iterators to objects of the class linkedListType

Will have one member variable to refer to the current node

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

34

Linked List Iterators (3 of 4)

FIGURE 16-19 UML class diagram of the class linkedListIterator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

35

Linked List Iterators (4 of 4)

FIGURE 16-20 UML class diagram of the class linkedListType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

36

Default Constructor

Default constructor:

Initializes the list to an empty state

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

37

Destroy the List

Function destroyList:

Traverses the list to deallocate memory occupied by each node

Once list is destroyed, sets pointers first and last to nullptr and count to 0

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

38

Initialize the List

Function initializeList:

Initializes list to an empty state

Since constructor already did this, initializeList is used to reinitialize an existing list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

39

Print the List

Function print:

Prints data contained in each node

Traverses the list using another pointer

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

40

Length of a List

Function length:

Returns the count of nodes in the list

Uses the count variable

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

41

Retrieve the Data of the First or Last Node

Function front:

Returns the info contained in the first node

If list is empty, program will be terminated

Function back:

Returns the info contained in the last node

If list is empty, program will be terminated

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

42

Begin and End

Function begin:

Returns an iterator to the first node in the list

Function end:

Returns an iterator to one past the last node in the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

43

Copy the List

Function copyList:

Makes an identical copy of a linked list

Steps:

Create a node called newNode

Copy the info of the original node into newNode

Insert newNode at the end of the list being created

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

44

Destructor & Copy Constructor

Destructor:

Deallocates memory occupied by nodes when the class object goes out of scope

Calls destroyList to traverse the list and delete each node

Copy constructor:

Makes an identical copy of the linked list

Calls function copyList

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

45

Overloading the Assignment Operator

Definition of the function to overload the assignment operator

Similar to the copy constructor

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

46

Unordered Linked Lists (1 of 2)

class unorderedLinkedList

Derived from the abstract class linkedListType

Implements the operations search, insertFirst, insertLast, and deleteNode

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

47

Unordered Linked Lists (2 of 2)

FIGURE 16-19 UML class diagram of the class linkedListIterator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

48

Unordered Linked List: Search the List

Function search:

Searches the list for a given item

Steps:

Compare search item with current node in the list

If info of current node is the same as search item, stop the search

Otherwise, make the next node the current node

Repeat Step 1 until item is found or until no more data is left in the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

49

Insert the First Node

Function insertFirst:

Inserts a new item at the beginning of the list

Steps:

Create a new node

Store the new item in the new node

Insert the node before first

Increment count by 1

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

50

Insert the Last Node

Function insertLast:

Inserts a new node after last

Similar to insertFirst function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

51

Delete a Node (1 of 6)

Function deleteNode:

Deletes a node with given info from the list

Several possible cases to manage

Case 1: List is empty

If the list is empty, output an error message

Case 2: Node to be deleted is the first node

Adjust the pointer first and count

If no other nodes, set first and last to nullptr

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

52

Delete a Node (2 of 6)

FIGURE 16-23 list with more than one node

FIGURE 16-24 list after deleting node with info 28

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

53

Delete a Node (3 of 6)

Case 3: Node to be deleted is not the first one

Case 3a: Node to be deleted is not last one

Update link field of the previous node

Case 3b: Node to be deleted is the last node

Update link field of the previous node to nullptr

Update last pointer to point to previous node

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

54

Delete a Node (4 of 6)

FIGURE 16-25 list before deleting 37

FIGURE 16-26 list after deleting 37

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

55

Delete a Node (5 of 6)

FIGURE 16-27 list before deleting 54

FIGURE 16-28 list after deleting 54

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

56

Delete a Node (6 of 6)

Case 4: Node to be deleted is not in the list

List requires no adjustment

Simply output an error message

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

57

Ordered Linked Lists (1 of 2)

orderedLinkedList: derived from class linkedListType

Provides definitions of the abstract functions insertFirst, insertLast, search, and deleteNode

Assume that elements of an ordered linked list are arranged in ascending order

Include the function insert to insert an element in an ordered list at its proper place

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

58

Ordered Linked Lists (2 of 2)

FIGURE 16-29 UML class diagram of the class orderedLinkedList and the inheritance hierarchy

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

59

Ordered Linked Lists: Search the List

Steps:

Compare the search item with the current node in the list

If info of current node is >= to search item, stop search

Otherwise, make the next node the current node

Repeat Step 1 until an item in the list >= to search item is found, or no more data is left in the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

60

Insert a Node (1 of 5)

Case 1: The list is empty

New node becomes first node

FIGURE 16-30 list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

61

Insert a Node (2 of 5)

Case 2: List is not empty, and the item to be inserted is smaller than smallest item in list

New node goes at beginning of list

FIGURE 16-32 list after inserting 10

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

62

Insert a Node (3 of 5)

Case 3: New item to be inserted somewhere in list

Case 3a: New item is larger than largest item

New item is inserted at end of list

Case 3b: Item to be inserted goes somewhere in the middle of the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

63

Insert a Node (4 of 5)

FIGURE 16-33 list before inserting 65

FIGURE 16-34 list after inserting 65

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

64

Insert a Node (5 of 5)

FIGURE 16-35 list before inserting 27

FIGURE 16-36 list after inserting 27

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

65

Insert First and Insert Last

Functions insertFirst and insertLast

Must insert new item at the proper place to ensure resulting list is still sorted

These functions are not actually used

Definitions must be provided because they are declared as abstract in the parent class

Function insertNode is used to insert at the proper place

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

66

Delete a Node

Case 1: List is initially empty  error

Case 2: Item to be deleted is first node in list

Adjust the head (first) pointer

Case 3: Item is somewhere in the list

current points to node with item to delete

trailCurrent points to node previous to the one pointed to by current

Case 4: Item is not in the list error

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

67

Print a Linked List in Reverse Order (Recursion Revisited)

Links are only in forward direction

Cannot traverse list backward using links

Can use recursion

List is printed only if pointer to the list is not nullptr

Recursive call is on the tail of the list

When tail is empty, recursion stops

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

68

Doubly Linked Lists (1 of 2)

Doubly linked list: every node has next and back pointers

Can be traversed in either direction

FIGURE 16-39 Doubly linked list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

69

Doubly Linked Lists (2 of 2)

Operations:

Initialize or destroy the list

Determine whether the list is empty

Search the list for a given item

Retrieve the first or last element of the list

Insert or delete an item

Find the length of the list

Print the list

Make a copy of the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

70

Doubly Linked List: Default Constructor

Default constructor:

Initializes doubly-linked list to empty state

Sets first and last to nullptr, and count to 0

isEmptyList:

Returns true if list is empty, false otherwise

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

71

Destroy the List & Initialize the List

Function destroy:

Deletes all the nodes in the list, leaving list in an empty state

Sets count to 0

Function initializeList:

Reinitializes doubly linked list to an empty state

Uses the destroy operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

72

Length of the List & Print the List

Function length

Returns the count of nodes in the list

Function print

Traverses the list

Outputs the info contained in each node

Function reversePrint

Traverses list in reverse order using back links

Outputs the info in each node

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

73

Doubly Linked List: Search the List

Function search:

Returns true if search item is found, otherwise false

Algorithm is same as that for an ordered linked list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

74

First and Last Elements

Function front

Returns first element of the list

Function back

Returns last element of the list

If list is empty, both functions will terminate the program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

75

Insert a Node (1 of 2)

Four insertion cases:

Case 1: Insertion in an empty list

Case 2: Insertion at beginning of a nonempty list

Case 3: Insertion at end of a nonempty list

Case 4: Insertion somewhere in nonempty list

Cases 1 & 2 require update to pointer first

Cases 3 & 4 are similar:

After inserting item, increment count by 1

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

76

Insert a Node (2 of 2)

FIGURE 16-40 Doubly linked list before inserting 20

FIGURE 16-41 Doubly linked list after inserting 20

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

77

Delete a Node (1 of 3)

Case 1: The list is empty

Case 2: The item to be deleted is first node in list

Must update the pointer first

Case 3: Item to be deleted is somewhere in the list

Case 4: Item to be deleted is not in the list

After deleting a node, count is decremented by 1

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

78

Delete a Node (2 of 3)

FIGURE 16-42 Doubly linked list before deleting 17

FIGURE 16-43 Doubly linked list after deleting 17

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

79

Delete a Node (3 of 3)

FIGURE 16-44 List after deleting the node with info 17

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

80

Circular Linked Lists (1 of 2)

Circular linked list: a linked list in which the last node points to the first node

FIGURE 16-45 Circular linked lists

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

81

Circular Linked Lists (2 of 2)

Operations on a circular list:

Initialize the list (to an empty state)

Determine if the list is empty

Destroy the list

Print the list

Find the length of the list

Search the list for a given item

Insert or delete an item

Copy the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

82

Summary (1 of 3)

A linked list is a list of items (nodes)

Order of the nodes is determined by the address (link) stored in each node

Pointer to a linked list is called head or first

A linked list is a dynamic data structure

The list length is the number of nodes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

83

Summary (2 of 3)

Insertion and deletion does not require data movement

Only the pointers are adjusted

A (single) linked list is traversed in only one direction

Search of a linked list is sequential

The head pointer is fixed on first node

Traverse: use a pointer other than head

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

84

Summary (3 of 3)

Doubly linked list

Every node has two links: next and previous

Can be traversed in either direction

Item insertion and deletion require the adjustment of two pointers in a node

A linked list in which the last node points to the first node is called a circular linked list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

‹#›

85

9781337117562_ppt_ch17.pptx

Chapter 17

Stacks and Queues

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

Objectives (1 of 2)

In this chapter, you will:

Learn about stacks

Examine various stack operations

Learn how to implement a stack as an array

Learn how to implement a stack as a linked list

Learn about infix, prefix, and postfix expressions, and how to use a stack to evaluate postfix expressions

C© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

++ Programming: From Problem Analysis to Program Design, Seventh Edition

2

‹#›

2

Objectives (2 of 2)

Learn how to use a stack to remove recursion

Learn about queues

Examine various queue operations

Learn how to implement a queue as an array

Learn how to implement a queue as a linked list

Discover how to use queues to solve simulation problems

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

3

‹#›

3

Stacks (1 of 4)

Stack: a data structure in which elements are added and removed from one end only

Addition/deletion occur only at the top of the stack

Last in first out (LIFO) data structure

Operations:

Push: to add an element onto the stack

Pop: to remove an element from the stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

4

‹#›

4

Stacks (2 of 4)

FIGURE 17-1 Various types of stacks

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

5

‹#›

5

Stacks (3 of 4)

FIGURE 17-2 Empty stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

6

‹#›

6

Stacks (4 of 4)

FIGURE 17-3 Stack operations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

7

‹#›

7

Stack Operations

In the abstract class stackADT:

initializeStack

isEmptyStack

isFullStack

push

top

pop

FIGURE 17-4 UML class diagram of the class stackADT

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

8

‹#›

8

Implementation of Stacks as Arrays (1 of 5)

First element goes in first array position, second in the second position, etc.

Top of the stack is index of the last element added to the stack

Stack elements are stored in an array, which is a random access data structure

Stack element is accessed only through top

To track the top position, use a variable called stackTop

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

9

‹#›

9

Implementation of Stacks as Arrays (2 of 5)

Can dynamically allocate array

Enables user to specify size of the array

class stackType implements the functions of the abstract class stackADT

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

10

‹#›

10

Implementation of Stacks as Arrays (3 of 5)

FIGURE 17-5 UML class diagram of the class stackType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

11

‹#›

11

Implementation of Stacks as Arrays (4 of 5)

C++ arrays begin with the index 0

Must distinguish between:

Value of stackTop

Array position indicated by stackTop

If stackTop is 0, stack is empty

If stackTop is nonzero, stack is not empty

Top element is given by stackTop - 1

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

12

‹#›

12

Implementation of Stacks as Arrays (5 of 5)

FIGURE 17-6 Example of a stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

13

‹#›

13

Initialize Stack

FIGURE 17-7 Empty stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

14

‹#›

14

Empty Stack/Full Stack

Stack is empty if stackTop = 0

Stack is full if stackTop = maxStackSize

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

15

‹#›

15

Push (1 of 3)

Store the newItem in the array component indicated by stackTop

Increment stackTop

Overflow occurs if we try to add a new item to a full stack

C++ Progra© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

mming: From Problem Analysis to Program Design, Seventh Edition

16

‹#›

16

Push (2 of 3)

FIGURE 17-8 Stack before pushing y

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

17

‹#›

17

Push (3 of 3)

FIGURE 17-9 Stack after pushing y

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

18

‹#›

18

Return the Top Element

top operation:

Returns the top element of the stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

19

‹#›

19

Pop (1 of 3)

To remove an element from the stack, decrement stackTop by 1

Underflow condition: trying to remove an item from an empty stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

20

‹#›

20

Pop (2 of 3)

FIGURE 17-10 Stack before popping D

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

21

‹#›

21

Pop (3 of 3)

FIGURE 17-11 Stack after popping D

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

22

‹#›

22

Copy Stack

copyStack function: copies a stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

23

‹#›

23

Constructor and Destructor

Constructor:

Sets stack size to parameter value (or default value if not specified)

Sets stackTop to 0

Creates array to store stack elements

Destructor:

Deallocates memory occupied by the array

Sets stackTop to 0

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

24

‹#›

24

Copy Constructor

Copy constructor:

Called when a stack object is passed as a (value) parameter to a function

Copies values of member variables from actual parameter to formal parameter

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

25

‹#›

25

Overloading the Assignment Operator (=) (1 of 2)

Assignment operator must be explicitly overloaded because of pointer member variables

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

26

‹#›

26

Stack Header File

Place definitions of class and functions (stack operations) together in a file

Called myStack.h

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

27

‹#›

27

Linked Implementation of Stacks (1 of 2)

Array only allows fixed number of elements

If number of elements to be pushed exceeds array size, the program may terminate

Linked lists can dynamically organize data

In a linked representation, stackTop is pointer to memory address of top element in stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

28

‹#›

28

Linked Implementation of Stacks (2 of 2)

FIGURE 17-12 Empty and nonempty linked stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

29

‹#›

29

Default Constructor

Initializes the stack to an empty state when a stack object is declared

Sets stackTop to nullptr

template <class Type>

linkedStackType<Type>::linkedStackType()

{

stackTop = nullptr;

}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

30

‹#›

30

Empty Stack and Full Stack

In a linked implementation of stacks, function isFullStack does not apply

Logically, the stack is never full

Stack is empty if stackTop is nullptr

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

31

‹#›

31

Linked Stack: Initialize Stack

initializeStack: reinitializes stack to an empty state

Must deallocate memory occupied by current element

Sets stackTop to nullptr

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

32

‹#›

32

Push (1 of 2)

newNode is added at the beginning of the linked list pointed to by stackTop

FIGURE 17-13 Stack before the push operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

33

‹#›

33

Push (2 of 2)

FIGURE 17-14 Push operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

34

‹#›

34

Linked Stack: Return the Top Element

template <class Type>

Type linkedStackType<Type>::top() const

{

assert(stackTop != nullptr); //if stack is empty,

//terminate the program

return stackTop->info; //return the top element

}//end top

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

35

‹#›

35

Pop (1 of 2)

Node pointed to by stackTop is removed

Second element becomes top element

FIGURE 17-15 Stack before the pop operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

36

‹#›

36

Pop (2 of 2)

FIGURE 17-16 Pop operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

37

‹#›

37

Linked Stack: Copy Stack

copyStack function: makes an identical copy of a stack

Similar definition to copyList for linked lists

C++ Pro© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

gramming: From Problem Analysis to Program Design, Seventh Edition

38

‹#›

38

Constructors and Destructors

Copy constructor and destructor:

Similar to those for linked lists

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

39

‹#›

39

Overloading the Assignment Operator (=) (2 of 2)

Overloading the assignment operator:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

40

‹#›

40

Stack as Derived from the class unorderedLinkedList

Implementation of push is similar to insertFirst for general lists

Other similar functions:

initializeStack and initializeList

isEmptyList and isEmptyStack

linkedStackType can be derived from linkedListType

class linkedListType is abstract

unorderedLinkedListType is derived from linkedListType

Provides the definitions of the abstract functions of the class linkedListType

linkedStackType is derived from unorderedLinkedListType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

41

‹#›

41

Application of Stacks: Postfix Expressions Calculator (1 of 8)

Infix notation: usual notation for writing arithmetic expressions

Operator is written between the operands

Example: a + b

Evaluates from left to right

Operators have precedence

Parentheses can be used to override precedence

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

42

‹#›

42

Application of Stacks: Postfix Expressions Calculator (2 of 8)

Prefix (Polish) notation: operators are written before the operands

Introduced by the Polish mathematician Jan Lukasiewicz in early 1920s

Parentheses can be omitted

Example: + a b

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

43

‹#›

43

Application of Stacks: Postfix Expressions Calculator (3 of 8)

Reverse Polish notation: operators follow the operands (postfix operators)

Proposed by Australian philosopher and early computer scientist Charles L. Hamblin in the late 1950s

Advantage: operators appear in the order required for computation

Example: a + b * c becomes a b c * +

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

44

‹#›

44

Application of Stacks: Postfix Expressions Calculator (4 of 8)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

45

‹#›

45

Application of Stacks: Postfix Expressions Calculator (5 of 8)

Postfix notation has important applications in computer science

Many compilers first translate arithmetic expressions into postfix notation and then translate this expression into machine code

Evaluation algorithm:

Scan expression from left to right

When an operator is found, back up to get operands, perform the operation, and continue

C© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

+ Programming: From Problem Analysis to Program Design, Seventh Edition

46

‹#›

46

Application of Stacks: Postfix Expressions Calculator (6 of 8)

FIGURE 17-17 Evaluating the postfix expression: 6 3 + 2 * =

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

47

‹#›

47

Application of Stacks: Postfix Expressions Calculator (7 of 8)

Symbols can be numbers or anything else:

+, -, *, and / are operators, require two operands

Pop stack twice and evaluate expression

If stack has less than two elements  error

If symbol is =, expression ends

Pop and print answer from stack

If stack has more than one element  error

If symbol is anything else

Expression contains an illegal operator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

48

‹#›

48

Application of Stacks: Postfix Expressions Calculator (8 of 8)

Assume postfix expressions are in this form:

#6 #3 + #2 * =

If symbol scanned is #, next input is a number

If the symbol scanned is not #, then it is:

An operator (may be illegal) or

An equal sign (end of expression)

Assume expressions contain only +, -, *, and / operators

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

49

‹#›

49

Main Algorithm

Pseudocode:

Four functions are needed:

evaluateExpression, evaluateOpr, discardExp, and printResult

C+© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

+ Programming: From Problem Analysis to Program Design, Seventh Edition

50

‹#›

50

Function evaluateExpression

Function evaluateExpression:

Evaluates each postfix expression

Each expression ends with = symbol

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

51

‹#›

51

Function evaluateOpr

Function evaluateOpr:

Evaluates an expression

Needs two operands saved in the stack

If less than two  error

Also checks for illegal operations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

52

‹#›

52

Function discardExp

Function discardExp:

Called when an error is discovered in expression

Reads and writes input data until the ‘=’

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

53

‹#›

53

Function printResult

The function printResult: If the postfix expression contains no errors, it prints the result

Otherwise, it outputs an appropriate message

Result of the expression is in the stack, and output is sent to a file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

54

‹#›

54

To print a list backward nonrecursively, first get to the last node of the list

Problem: Links go in only one direction

Solution: Save a pointer to each of node in a stack

Uses the LIFO principle

Since number of nodes is usually not known, use the linked implementation of a stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

55

Nonrecursive Algorithm to Print a Linked List Backward (1 of 7)

‹#›

55

Nonrecursive Algorithm to Print a Linked List Backward (2 of 7)

FIGURE 17-18 Linked list

FIGURE 17-19 List after the statement current = first; executes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

ramming: From Problem Analysis to Program Design, Seventh Edition

56

‹#›

56

Nonrecursive Algorithm to Print a Linked List Backward (3 of 7)

FIGURE 17-20 List and stack after the statements stack.push(current); and current = current->link; execute

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

57

‹#›

57

Nonrecursive Algorithm to Print a Linked List Backward (4 of 7)

FIGURE 17-21 List and stack after the statements stack.push(current); and current = current->link; execute

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

58

‹#›

58

Nonrecursive Algorithm to Print a Linked List Backward (5 of 7)

FIGURE 17-22 List and stack after the statements stack.push(current); and current =current->link; execute

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

59

‹#›

59

Nonrecursive Algorithm to Print a Linked List Backward (6 of 7)

FIGURE 17-23 List and stack after the statements current = stack.top(); and stack. pop(); execute

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

60

‹#›

60

Nonrecursive Algorithm to Print a Linked List Backward (7 of 7)

FIGURE 17-24 List and stack after the statements current=stack.top(); and stack.pop(); execute

FIGURE 17-25 List and stack after the statements current=stack.top(); and stack.pop(); execute

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

61

‹#›

61

Queues

Queue: set of elements of the same type

Elements are:

Added at one end (the back or rear)

Deleted from the other end (the front)

First In First Out (FIFO) data structure

Middle elements are inaccessible

Example:

Waiting line in a bank

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

62

‹#›

Queue Operations

Queue operations include:

initializeQueue

isEmptyQueue

isFullQueue

front

back

addQueue

deleteQueue

Abstract class queueADT defines these operations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

63

‹#›

63

Implementation of Queues as Arrays (1 of 15)

Need at least four (member) variables:

Array to store queue elements

queueFront and queueRear

To track first and last elements

maxQueueSize

To specify maximum size of the queue

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

64

‹#›

64

Implementation of Queues as Arrays (2 of 15)

To add an element to the queue:

Advance queueRear to next array position

Add element to position pointed by queueRear

FIGURE 17-26 Queue after the first addQueue operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

65

‹#›

65

Implementation of Queues as Arrays (3 of 15)

FIGURE 17-27 Queue after two more addQueue operations

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

66

‹#›

66

Implementation of Queues as Arrays (4 of 15)

To delete an element from the queue:

Retrieve element pointed to by queueFront

Advance queueFront to next queue element

FIGURE 17-28 Queue after the deleteQueue operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

67

‹#›

67

Implementation of Queues as Arrays (5 of 15)

Will this queue design work?

Let A represent adding an element to the queue

Let D represent deleting an element from the queue

Consider the following sequence of operations:

AAADADADADADADADA...

C++ Programming: From Problem © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

Analysis to Program Design, Seventh Edition

68

‹#›

68

Implementation of Queues as Arrays (6 of 15)

This would eventually set queueRear to point to the last array position

Giving the impression that the queue is full

FIGURE 17-29 Queue after the sequence of operations AAADADADADADA . . .

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

69

‹#›

69

Implementation of Queues as Arrays (7 of 15)

Solution 1: When queue overflows at rear (queueRear points to the last array position):

Check value of queueFront

If queueFront indicates there is room at front of array, slide all queue elements toward the first array position

Problem: too slow for large queues

Solution 2: Assume that the array is circular

C++ Program© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

ming: From Problem Analysis to Program Design, Seventh Edition

‹#›

70

Implementation of Queues as Arrays 8 of 15)

FIGURE 17-30 Circular queue

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

71

‹#›

71

Implementation of Queues as Arrays (9 of 15)

FIGURE 17-31 Queue before and after the add operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

72

‹#›

72

Implementation of Queues as Arrays (10 of 15)

Deletion Case 1:

FIGURE 17-32 Queue before and after the delete operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

73

‹#›

73

Implementation of Queues as Arrays (11 of 15)

Deletion Case 2:

FIGURE 17-33 Queue before and after the add operation

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

74

‹#›

74

Implementation of Queues as Arrays (12 of 15)

Problem:

Figures 17-32b and 17-33b have identical values for queueFront and queueRear

However, Figure 17-32b represents an empty queue, whereas Figures 17-33b shows a full queue

Solution?

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

75

‹#›

75

Implementation of Queues as Arrays (13 of 15)

Solution 1: keep a count

Incremented when a new element is added to the queue

Decremented when an element is removed

Initially set to 0

Very useful if user (of queue) frequently needs to know the number of elements in the queue

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

76

‹#›

76

Implementation of Queues as Arrays (14 of 15)

Solution 2: Let queueFront indicate index of array position preceding the first element

queueRear still indicates index of last one

Queue empty if:

queueFront == queueRear

Slot indicated by queueFront is reserved

Queue is full if next available space is the reserved slot indicated by queueFront

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

77

‹#›

77

Implementation of Queues as Arrays (15 of 15)

FIGURE 17-34 Array to store the queue elements with a reserved slot

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

78

‹#›

78

Empty Queue and Full Queue

Queue is empty if count ==0

Queue is full if count == maxQueueSize

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

79

‹#›

79

Initialize Queue

Initializes queue to empty state

First element is added at first array position

queueFront set to 0

queueRear set to maxQueueSize -1

count set to 0

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

80

FIGURE 17-35 Empty queue

‹#›

80

Front and Back

front operation: returns the first element of the queue

If queue is empty, program terminates

back operation: returns the last element of the queue

If queue is empty, program terminates

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

81

‹#›

81

addQueue

addQueue operation:

Advance queueRear to next array position

Add new element to array position indicated by queueRear

Increment count by 1

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

82

‹#›

82

deleteQueue

deleteQueue operation:

Decrement count by 1

Advance queueFront to next queue element

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

83

‹#›

83

Queue: Constructors and Destructors

Constructor:

Sets maxQueueSize to user specification

Creates array of size maxQueueSize (or default size)

Initializes queueFront and queueRear to indicate empty queue

Destructor:

Deallocates memory occupied by array

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

84

‹#›

84

Linked Implementation of Queues (1 of 2)

Array implementation has issues:

Array size is fixed: only a finite number of queue elements can be stored in it

Requires array to be treated in a special way, together with queueFront and queueRear

Linked implementation of a queue simplifies many issues

Queue is never full because memory is allocated dynamically

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

85

Linked Implementation of Queues (2 of 2)

Elements are added at one end and removed from the other

Need only two pointers to maintain the queue: queueFront and queueRear

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

86

‹#›

86

Empty and Full Queue

Queue is empty if queueFront is nullptr

Queue is never full

Unless the system runs out of memory

Note: must provide isFullQueue function definition because it is an abstract function in parent class queueADT

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

87

‹#›

87

Linked Queue: Initialize Queue

Initializes queue to an empty state

Must remove all existing elements, if any

Deallocates memory occupied by elements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

88

‹#›

88

addQueue, front, back, and deleteQueue operations

addQueue operation: adds new element to end of queue

front operation: returns first element of queue

back operation: returns last element of queue

deleteQueue operation: removes first element of queue

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

89

‹#›

89

Linked Queue: Constructors and Destructors

Constructor

Accesses maxQueueSize, queueFront, and queueRear

Destructor: destroys the queue

Deallocates memory occupied by elements

Copy constructor and overloading assignment operator:

Similar to corresponding function for stack

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

90

‹#›

90

Queue Derived from the class unorderedLinkedListType

Linked implementation of queue: similar to implementation of a linked list created in a forward manner

addQueue similar to insertFirst

initializeQueue is like initializeList

isEmptyQueue similar to isEmptyList

deleteQueue can be implemented as before

queueFront is same as first

queueRear is same as last

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

91

Application of Queues: Simulation

Simulation: a technique in which one system models the behavior of another system

Computer models are used to study the behavior of real systems

Queuing systems: computer simulations using queues as the data structure

Queues of objects are waiting to be served

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

92

‹#›

92

Designing a Queuing System (1 of 3)

Server: object that provides the service

Customer: object receiving the service

Transaction time: service time, or the time it takes to serve a customer

Model: system that consists of a list of servers and a waiting queue holding the customers to be served

Customer at front of queue waits for the next available server

C++ Programming: From © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

Problem Analysis to Program Design, Seventh Edition

‹#›

93

Designing a Queuing System (2 of 3)

Need to know:

Number of servers

Expected arrival time of a customer

Time between the arrivals of customers

Number of events affecting the system

Performance of system depends on:

How many servers are available

How long it takes to serve a customer

How often a customer arrives

C++© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

Programming: From Problem Analysis to Program Design, Seventh Edition

‹#›

94

Designing a Queuing System (3 of 3)

If it takes too long to serve a customer and customers arrive frequently, then more servers are needed

System can be modeled as a time-driven simulation

Time-driven simulation: the clock is a counter

The passage of one unit of time can be implemented by incrementing a counter by 1

Simulation is run for a fixed amount of time

C++ Pro© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

gramming: From Problem Analysis to Program Design, Seventh Edition

‹#›

95

Customer

FIGURE 17-36 UML class diagram of the class customerType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

96

‹#›

96

Server

FIGURE 17-37 UML class diagram of the class serverType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

97

‹#›

97

Server List

Server list: a set of servers

At any given time, a server is either free or busy

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

98

FIGURE 17-38 UML class diagram of the class serverListType

‹#›

98

Waiting Customers Queue

When customer arrives, he/she goes to end of queue

When a server becomes available, customer at front of queue leaves to conduct the transaction

After each time unit, the waiting time of each customer in the queue is incremented by 1

Can use queueType but must add an operation to increment waiting time

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

99

‹#›

99

Main Program

Algorithm for main loop:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

100

‹#›

100

Summary (1 of 2)

Stack: items are added/deleted from one end

Last In First Out (LIFO) data structure

Operations: push, pop, initialize, destroy, check for empty/full stack

Can be implemented as array or linked list

Middle elements should not be accessed directly

Postfix notation: operators are written after the operands (no parentheses needed)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

C++ Programming: From Problem Analysis to Program Design, Seventh Edition

101

‹#›

101

Summary (2 of 2)

Queue: items are added at one end and removed from the other end

First In First Out (FIFO) data structure

Operations: add, remove, initialize, destroy, check if queue is empty/full

Can be implemented as array or linked list

Middle elements should not be accessed directly

Is a restricted version of array and linked list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

102

‹#›

102

9781337117562_ppt_ch18.pptx

Chapter 18

Searching and Sorting Algorithms

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

C++ Programming: From Problem Analysis to Program Design, Eighth Edition

‹#›

1

Objectives

In this chapter, you will:

Learn about the various search algorithms

Explore how to implement the sequential search algorithm and how it performs

Explore how to implement the binary search algorithm and how it performs

Learn about the asymptotic notation, Big-O, used in algorithm analysis

Become familiar with the lower bound on comparison-based search algorithms

Learn about the various sorting algorithms

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Introduction

Using a search algorithm, you can:

Determine whether a particular item is in a list

If the data is specially organized (for example, sorted), find the location in the list where a new item can be inserted

Find the location of an item to be deleted

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Searching and Sorting Algorithms

Data can be organized with the help of an array or a linked list

unorderedLinkedList

unorderedArrayListType

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Search Algorithms

Key of the item

Special member that uniquely identifies the item in the data set

Key comparison: comparing the key of the search item with the key of an item in the list

Can count the number of key comparisons

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Sequential Search

Sequential search (linear search):

Same for both array-based and linked lists

Starts at first element and examines each element until a match is found

Our implementation uses an iterative approach

Can also be implemented with recursion

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Sequential Search Analysis (1 of 2)

Statements before and after the loop are executed only once

Require very little computer time

Statements in the while loop repeated several times

Execution of the other statements in loop is directly related to outcome of key comparison

Speed of a computer does not affect the number of key comparisons required

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Sequential Search Analysis (2 of 2)

L: a list of length n

If search item (target) is not in the list: n comparisons

If the search item is in the list:

As first element of L  1 comparison (best case)

As last element of L  n comparisons (worst case)

Average number of comparisons:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Binary Search (1 of 3)

Binary search can be applied to sorted lists

Uses the “divide and conquer” technique

Compare search item to middle element

If search item is less than middle element, restrict the search to the lower half of the list

Otherwise restrict the search to the upper half of the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Binary Search (2 of 3)

FIGURE 18-1 List of length 12

FIGURE 18-2 Search list, list[0] . . . list[11]

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Binary Search (3 of 3)

Search for value of 75:

FIGURE 18-3 Search list, list[6]...list[11]

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Performance of Binary Search

Every iteration cuts size of the search list in half

If list L has 1024 = 210 items

At most 11 iterations needed to find x

Every iteration makes two key comparisons

In this case, at most 22 key comparisons

Max # of comparisons = 2log2n+2

Sequential search required 512 key comparisons (average) to find if x is in L

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Binary Search Algorithm and the class orderedArrayListType

To use binary search algorithm in class orderedArrayListType:

Add binSearch function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Asymptotic Notation: Big-O Notation (1 of 8)

After an algorithm is designed, it should be analyzed

May be various ways to design a particular algorithm

Certain algorithms take very little computer time to execute

Others take a considerable amount of time

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Asymptotic Notation: Big-O Notation (2 of 8)

TABLE 18-4 Growth Rate of Various Functions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Asymptotic Notation: Big-O Notation (3 of 8)

TABLE 18-5 Time for f(n) Instructions on a Computer That Executes 1 Billion Instructions per Second

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Asymptotic Notation: Big-O Notation (4 of 8)

FIGURE 18-5 Growth rate of various functions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Asymptotic Notation: Big-O Notation (5 of 8)

Let f be a function of n

Asymptotic: the study of the function f as n becomes larger and larger without bound

Let f and g be real-valued, non-negative functions

f(n) is Big-O of g(n), written f(n)=O(g(n)) if there are constants c and n0 such that

f(n)≤cg(n) for all n ≥n0

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Asymptotic Notation: Big-O Notation (6 of 8)

TABLE 18-6 Growth Rate of n2 and n2 + 4n + 20

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Asymptotic Notation: Big-O Notation (7 of 8)

TABLE 18-7 Some Big-O Functions That Appear in Algorithm Analysis

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Asymptotic Notation: Big-O Notation (8 of 8)

We can use Big-O notation to compare sequential and binary search algorithms:

TABLE 18-8 Number of Comparisons for a List of Length n

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Lower Bound on Comparison-Based Search Algorithms

Comparison-based search algorithms:

Search a list by comparing the target element with list elements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Sorting Algorithms

To compare the performance of commonly used sorting algorithms

Must provide some analysis of these algorithms

These sorting algorithms can be applied to either array-based lists or linked lists

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Sorting a List: Bubble Sort (1 of 3)

Suppose list[0]...list[n–1] is a list of n elements, indexed 0 to n–1

Bubble sort algorithm:

In a series of n-1 iterations, compare successive elements, list[index] and list[index+1]

If list[index] is greater than list[index+1], then swap them

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Sorting a List: Bubble Sort (2 of 3)

FIGURE 18-7 Elements of list during the first iteration

FIGURE 18-8 Elements of list during the second iteration

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Sorting a List: Bubble Sort (3 of 3)

FIGURE 18-9 Elements of list during the third iteration

FIGURE 18-10 Elements of list during the fourth iteration

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Analysis: Bubble Sort

bubbleSort contains nested loops

Outer loop executes n – 1 times

For each iteration of outer loop, inner loop executes a certain number of times

Total number of comparisons:

Number of assignments (worst case):

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

Bubble Sort Algorithm and the class unorderedArrayListType

class unorderedArrayListType does not have a sorting algorithm

Must add function sort and call function bubbleSort instead

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

Selection Sort: Array-Based Lists

Selection sort algorithm: rearrange list by selecting an element and moving it to its proper position

Find the smallest (or largest) element and move it to the beginning (end) of the list

Can also be applied to linked lists

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

29

Analysis: Selection Sort

function swap: does three assignments; executed n−1 times

3(n − 1) = O(n)

function minLocation:

For a list of length k, k−1 key comparisons

Executed n−1 times (by selectionSort)

Number of key comparisons:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Insertion Sort: Array-Based Lists (1 of 6)

Insertion sort algorithm: sorts the list by moving each element to its proper place in the sorted portion of the list

FIGURE 18-11 list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

Insertion Sort: Array-Based Lists (2 of 6)

FIGURE 18-12 Sorted and unsorted portion of list

FIGURE 18-13 Move list[4] into list[2]

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

Insertion Sort: Array-Based Lists (3 of 6)

FIGURE 18-14 Copy list[4] into temp

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

Insertion Sort: Array-Based Lists (4 of 6)

FIGURE 18-15 List before copying list[3] into list[4] and then list[2] into list[3]

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

Insertion Sort: Array-Based Lists (5 of 6)

FIGURE 18-16 List after copying list[3] into list[4] and then list[2] into list[3]

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

Insertion Sort: Array-Based Lists (6 of 6)

FIGURE 18-17 List after copying temp into list[2]

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Analysis: Insertion Sort (1 of 2)

The for loop executes n – 1 times

Best case (list is already sorted):

Key comparisons: n – 1 = O(n)

Worst case: for each for iteration, if statement evaluates to true

Key comparisons: 1 + 2 + … + (n – 1) = n(n – 1) / 2 = O(n2)

Average number of key comparisons and of item assignments: ¼ n2 + O(n) = O(n2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Analysis: Insertion Sort (2 of 2)

TABLE 18-9 Average Case Behavior of the Bubble Sort, Selection Sort, and Insertion Sort Algorithms for a List of Length n

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Lower Bound on Comparison-Based Sort Algorithms (1 of 5)

Comparison tree: graph used to trace the execution of a comparison-based algorithm

Let L be a list of n distinct elements; n > 0

For any j and k, where 1  j  n, 1  k  n,

either L[j] < L[k] or L[j] > L[k]

Binary tree: each comparison has two outcomes

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

39

Lower Bound on Comparison-Based Sort Algorithms (2 of 5)

Node: represents a comparison

Labeled as j:k (comparison of L[j] with L[k])

If L[j] < L[k], follow the left branch; otherwise, follow the right branch

Leaf: represents final ordering of the nodes

Root: the top node

Branch: line that connects two nodes

Path: sequence of branches from one node to another

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Lower Bound on Comparison-Based Sort Algorithms (3 of 5)

FIGURE 18-18 Comparison tree for sorting three items

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

Lower Bound on Comparison-Based Sort Algorithms (4 of 5)

A unique permutation of the elements of L is associated with each root-to-leaf path

Because the sort algorithm only moves the data and makes comparisons

For a list of n elements, n > 0, there are n! different permutations

Any of these might be the correct ordering of L

Thus, the tree must have at least n! leaves

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

42

Lower Bound on Comparison-Based Sort Algorithms (5 of 5)

Theorem: Let L be a list of n distinct elements. Any sorting algorithm that sorts L by comparison of the keys only, in its worst case, makes at least O(nlog2n) key comparisons.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

43

Quick Sort: Array-Based Lists (1 of 9)

Quick sort: uses the divide-and-conquer technique

The list is partitioned into two sublists

Each sublist is then sorted

Sorted sublists are combined into one list in such a way that the combined list is sorted

All of the sorting work occurs during the partitioning of the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

44

Quick Sort: Array-Based Lists (2 of 9)

pivot element is chosen to divide the list into: lowerSublist and upperSublist

The elements in lowerSublist are < pivot

The elements in upperSublist are ≥ pivot

Pivot can be chosen in several ways

Ideally, the pivot divides the list into two sublists of

nearly- equal size

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

45

Quick Sort: Array-Based Lists (3 of 9)

FIGURE 18-19 list before the partition

FIGURE 18-20 list after the partition

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

46

Quick Sort: Array-Based Lists (4 of 9)

Partition algorithm (assumes that pivot is chosen as the middle element of the list):

Determine pivot; swap it with the first element of the list

For the remaining elements in the list:

If the current element is less than pivot, (1) increment smallIndex, and (2) swap current element with element pointed by smallIndex

Swap the first element (pivot), with the array element pointed to by smallIndex

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

47

Quick Sort: Array-Based Lists (5 of 9)

Step 1 determines the pivot and moves pivot to the first array position

During Step 2, list elements are arranged

FIGURE 18-21 List during the execution of Step 2

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

48

Quick Sort: Array-Based Lists (6 of 9)

FIGURE 18-22 List before sorting

FIGURE 18-23 List after moving pivot to the first array position

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

49

Quick Sort: Array-Based Lists (7 of 9)

FIGURE 18-24 List after a few iterations of Step 2

FIGURE 18-25 List after moving 11 into the lower sublist

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

50

Quick Sort: Array-Based Lists (8 of 9)

FIGURE 18-26 List before moving 58 into a sublist

FIGURE 18-27 List after moving 58 into the upper sublist

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

51

Quick Sort: Array-Based Lists (9 of 9)

FIGURE 18-28 List elements after arranging into the lower sublist and upper sublist

FIGURE 18-29 List after swapping 52 with 45

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

52

Analysis: Quick Sort

TABLE 18-10 Analysis of the Quick Sort Algorithm for a List of Length n

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

53

Merge Sort: Linked List-Based Lists (1 of 3)

Quick sort: O(nlog2n) average case; O(n2) worst case

Merge sort: always O(nlog2n)

Uses the divide-and-conquer technique

Partitions the list into two sublists

Sorts the sublists

Combines the sublists into one sorted list

Differs from quick sort in how list is partitioned

Divides list into two sublists of nearly equal size

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

54

Merge Sort: Linked List-Based Lists (2 of 3)

FIGURE 18-30 Merge sort algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

55

Merge Sort: Linked List-Based Lists (3 of 3)

General algorithm:

Uses recursion

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

56

Divide (1 of 2)

FIGURE 18-31 Unsorted linked list

FIGURE 18-32 middle and current before traversing the list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

57

Divide (2 of 2)

FIGURE 18-33 middle after traversing the list

FIGURE 18-34 List after dividing it into two lists

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

58

Merge (1 of 3)

Sorted sublists are merged into a sorted list

Compare elements of sublists

Adjust pointers of nodes with smaller info

FIGURE 18-35 Sublists before merging

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

59

Merge (2 of 3)

FIGURE 18-36 Sublists after setting newHead and lastMerged and advancing first1

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

60

Merge (3 of 3)

FIGURE 18-37 Merged list after putting the node with info 20 at the end of the merged list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

61

Analysis: Merge Sort (1 of 4)

Suppose that L is a list of n elements, with n > 0

Suppose that n is a power of 2; that is, n = 2m for some integer m > 0, so that we can divide the list into two sublists, each of size:

m will be the number of recursion levels

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

62

Analysis: Merge Sort (2 of 4)

FIGURE 18-38 Levels of recursion to recMergeSort for a list of length 8

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

63

Analysis: Merge Sort (3 of 4)

To merge two sorted lists of size s and t, the maximum number of comparisons is s + t  1

Function mergeList merges two sorted lists into a sorted list

This is where the actual comparisons and assignments are done

Max. # of comparisons at level k of recursion:

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

64

Analysis: Merge Sort (4 of 4)

The maximum number of comparisons at each level of the recursion is O(n)

Maximum number of comparisons is O(nm), where m = number of levels of recursion

Thus, O(nm)  O(n log2n)

W(n): # of key comparisons in worst case

A(n): # of key comparisons in average case

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

65

Summary (1 of 3)

On average, a sequential search searches half the list and makes O(n) comparisons

Not efficient for large lists

A binary search requires the list to be sorted

2log2n – 3 key comparisons

Let f be a function of n: by asymptotic, we mean the study of the function f as n becomes larger and larger without bound

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

66

Summary (2 of 3)

Binary search algorithm is the optimal worst-case algorithm for solving search problems by using the comparison method

To construct a search algorithm of the order less than log2n, it cannot be comparison based

Bubble sort: O(n2) key comparisons and item assignments

Selection sort: O(n2) key comparisons and O(n) item assignments

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

67

Summary (3 of 3)

Insertion sort: O(n2) key comparisons and item assignments

Both the quick sort and merge sort algorithms sort a list by partitioning it

Quick sort: average number of key comparisons is O(nlog2n); worst case number of key comparisons is O(n2)

Merge sort: number of key comparisons is O(nlog2n)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

68

9781337117562_ppt_ch19.pptx

Chapter 19

Binary Trees

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 2)

In this chapter, you will:

Learn about binary trees

Learn about the basic terminologies used in binary trees: left and right subtrees, path, height, level of a node, leaves, parent of a node

Explore various binary tree traversal algorithms

Explore how to implement the basic operations on a binary tree

Learn about binary search trees

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 2)

Learn how to organize data in a binary search tree

Learn how to insert and delete items in a binary search tree

Explore nonrecursive binary tree traversal algorithms

Explore binary tree traversal algorithms and functions as parameters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Binary Trees (1 of 7)

Definition: a binary tree T is either empty or has these properties:

Has a root node

Has two sets of nodes: left subtree LT and right subtree RT

LT and RT are binary trees

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Binary Trees (2 of 7)

FIGURE 19-1 Binary tree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

Binary Trees (3 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-2 Binary tree with one, two, or three nodes

‹#›

6

Binary Trees (4 of 7)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-3 Various binary trees with three nodes

‹#›

7

Binary Trees (5 of 7)

Every node has at most two children

A node:

Stores its own information

Keeps track of its left subtree and right subtree using pointers

lLink and rLink pointers

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Binary Trees (6 of 7)

A pointer to the root node of the binary tree is stored outside the tree in a pointer variable

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-4 Binary tree

‹#›

9

Binary Trees (7 of 7)

Leaf: node that has no left and right children

U is parent of V if there is a branch from U to V

There is a unique path from root to every node

Length of a path: number of branches on path

Level of a node: number of branches on the path from the root to the node

Root node level is 0

Height of a binary tree: number of nodes on the longest path from the root to a leaf

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

10

Copy Tree

Binary tree is a dynamic data structure

Memory is allocated/deallocated at runtime

Using just the value of the pointer of the root node makes a shallow copy of the data

To make an identical copy, must create as many nodes as are in the original tree

Use a recursive algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Binary Tree Traversal (1 of 4)

Insertion, deletion, and lookup operations require traversal of the tree

Must start at the root node

Two choices for each node:

Visit the node first

Visit the node’s subtrees first

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Binary Tree Traversal (2 of 4)

Inorder traversal

Traverse the left subtree

Visit the node

Traverse the right subtree

Preorder traversal

Visit the node

Traverse the left subtree

Traverse the right subtree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Binary Tree Traversal (3 of 4)

Postorder traversal

Traverse the left subtree

Traverse the right subtree

Visit the node

Listing of nodes produced by traversal type is called:

Inorder sequence

Preorder sequence

Postorder sequence

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Binary Tree Traversal (4 of 4)

Inorder sequence:

DFBACGE

Preorder sequence:

ABDFCEG

Postorder sequence:

FDBGECA

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-6 Binary tree for an inorder traversal

‹#›

15

Implementing Binary Trees (1 of 2)

Typical operations:

Determine whether the binary tree is empty

Search the binary tree for a particular item

Insert an item in the binary tree

Delete an item from the binary tree

Find the height of the binary tree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Implementing Binary Trees (2 of 2)

Typical operations (cont’d.):

Find the number of nodes in the binary tree

Find the number of leaves in the binary tree

Traverse the binary tree

Copy the binary tree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

17

Binary Search Trees (1 of 4)

Traverse the tree to determine whether 53 is in it - this is slow

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-7 Arbitrary binary tree

‹#›

18

Binary Search Trees (2 of 4)

In this binary tree, data in each node is:

Larger than data in its left child

Smaller than data in its right child

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-8 Binary search tree

‹#›

19

Binary Search Trees (3 of 4)

Definition: a binary search tree T is either empty or has these properties:

Has a root node

Has two sets of nodes: left subtree LT and right subtree RT

Key in root node is larger than every key in left subtree, and smaller than every key in right subtree

LT and RT are binary search trees

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Binary Search Trees (4 of 4)

Typical operations on a binary search tree:

Determine if it is empty

Search for a particular item

Insert or delete an item

Find the height of the tree

Find the number of nodes and leaves in the tree

Traverse the tree

Copy the tree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Search

Search steps:

Start search at root node

If no match, and search item is smaller than root node, follow lLink to left subtree

Otherwise, follow rLink to right subtree

Continue these steps until item is found or search ends at an empty subtree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Insert

After inserting a new item, resulting binary tree must be a binary search tree

Must find location where new item should be placed

Must keep two pointers, current and parent of current, in order to insert

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Delete (1 of 4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-9 Binary search tree before deleting a node

‹#›

24

Delete (2 of 4)

The delete operation has four cases:

The node to be deleted is a leaf

The node to be deleted has no left subtree

The node to be deleted has no right subtree

The node to be deleted has nonempty left and right subtrees

Must find the node containing the item (if any) to be deleted, then delete the node

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Delete (3 of 4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-10 Binary trees of Figure 19-9 after deleting various items

‹#›

26

Delete (4 of 4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-10 (cont’d.) Binary trees of Figure 19-9 after deleting various items

‹#›

27

Binary Search Tree: Analysis (1 of 4)

Let T be a binary search tree with n nodes, where n > 0

Suppose that we want to determine whether an item, x, is in T

The performance of the search algorithm depends on the shape of T

In the worst case, T is linear

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

28

Binary Search Tree: Analysis (2 of 4)

Worst case behavior: T is linear

O(n) key comparisons

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-11 Linear binary search trees

‹#›

29

Binary Search Tree: Analysis (3 of 4)

Average-case behavior:

There are n! possible orderings of the keys

We assume that orderings are possible

S(n) and U(n): number of comparisons in average successful and unsuccessful case, respectively

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

30

Binary Search Tree: Analysis (4 of 4)

Theorem: Let T be a binary search tree with n nodes, where n > 0

Average number of nodes visited in a search of T is approximately 1.39log2n=O(log2n)

Number of key comparisons is approximately 2.77log2n=O(log2n)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

31

Nonrecursive Binary Tree Traversal Algorithms

The traversal algorithms discussed earlier are recursive

This section discusses the nonrecursive inorder, preorder, and postorder traversal algorithms

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

32

Nonrecursive Inorder Traversal

For each node, the left subtree is visited first, then the node, and then the right subtree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 19-12 Binary tree; the leftmost node is 28

‹#›

33

Nonrecursive Preorder Traversal

For each node, first the node is visited, then the left subtree, and then the right subtree

Must save a pointer to a node before visiting the left subtree, in order to visit the right subtree later

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

Nonrecursive Postorder Traversal

Visit order: left subtree, right subtree, node

Must track for the node whether the left and right subtrees have been visited

Solution: Save a pointer to the node, and also save an integer value of 1 before moving to the left subtree and value of 2 before moving to the right subtree

When the stack is popped, the integer value associated with that pointer is popped as well

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

Binary Tree Traversal and Functions as Parameters (1 of 3)

In a traversal algorithm, “visiting” may mean different things

Example: output value; update value in some way

Problem:

How do we write a generic traversal function?

Writing a specific traversal function for each type of “visit” would be cumbersome

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Binary Tree Traversal and Functions as Parameters (2 of 3)

Solution:

Pass a function as a parameter to the traversal function

In C++, a function name without parentheses is considered a pointer to the function

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Binary Tree Traversal and Functions as Parameters (3 of 3)

To specify a function as a formal parameter to another function:

Specify the function type, followed by name as a pointer, followed by the parameter types

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Summary (1 of 3)

A binary tree is either empty or it has a special node called the root node

If nonempty, root node has two sets of nodes (left and right subtrees), such that the left and right subtrees are also binary trees

The node of a binary tree has two links in it

A node in the binary tree is called a leaf if it has no left and right children

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

39

Summary (2 of 3)

A node U is called the parent of a node V if there is a branch from U to V

Level of a node: number of branches on the path from the root to the node

The level of the root node of a binary tree is 0

The level of the children of the root is 1

Height of a binary tree: number of nodes on the longest path from the root to a leaf

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Summary (3 of 3)

Inorder traversal

Traverse left, visit node, traverse right

Preorder traversal

Visit node, traverse left, traverse right

Postorder traversal

Traverse left, traverse right, visit node

In a binary search tree:

Root node is larger than every node in left subtree

Root node is less than every node in right subtree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

9781337117562_PPT_ch20.pptx

Chapter 20

Graphs

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives

In this chapter, you will:

Learn about graphs

Become familiar with the basic terminology of graph theory

Discover how to represent graphs in computer memory

Explore graphs as ADTs

Examine and implement various graph traversal algorithms

Learn how to implement the shortest path algorithm

Examine and implement the minimal spanning tree algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Introduction (1 of 3)

Königsberg bridge problem

The river Pregel flows around the island Kneiphof and then divides into two branches

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-1 Königsberg bridge problem

‹#›

3

Introduction (2 of 3)

Starting at one land area, can you cross all bridges exactly once and return to the start?

In 1736, Euler represented the problem as a graph and answered the question: No

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-2 Graph representation of Königsberg bridge problem

‹#›

4

Introduction (3 of 3)

Over the past 200 years, graph theory has been applied to a variety of problems, including:

Model electrical circuits, chemical compounds, highway maps, etc.

Analysis of electrical circuits, finding the shortest route, project planning, linguistics, genetics, social science, etc.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Graph Definitions and Notations (1 of 8)

a  X: a is an element of the set X

Subset (Y  X): every element of Y is also an element of X

Intersection (A  B): contains all the elements in A and B

A  B = x | x  A and x  B

Union (A  B): set of all the elements that are in A or in B

A  B = x | x  A or x  B

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Graph Definitions and Notations (2 of 8)

A  B: set of all the ordered pairs of elements of A and B

A  B = (a, b) | a  A, b  B

Graph G: G = (V, E)

V is a finite nonempty set of vertices of G

E  V  V

Elements in E are the pairs of elements of V

E is called set of edges

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Graph Definitions and Notations (3 of 8)

Directed graph or digraph: elements of E(G) are ordered pairs

Undirected graph: elements not ordered pairs

If (u, v) is an edge in a directed graph

Origin: u

Destination: v

Subgraph H of G: if V(H)  V(G) and E(H)  E(G)

Every vertex and edge of V is in G

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Graph Definitions and Notations (4 of 8)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-3 Various undirected graphs

‹#›

9

Graph Definitions and Notations (5 of 8)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-4 Various directed graphs

‹#›

10

Graph Definitions and Notations (6 of 8)

Adjacent: there is an edge from one vertex to the other; i.e., (u, v)  E(G)

Incident: if edge e = (u, v), then e is incident on u and v

Loop: edge incident on a single vertex

Parallel edges: associated with the same pair of vertices

Simple graph: has no loops or parallel edges

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Graph Definitions and Notations (7 of 8)

Path: sequence of vertices u1, u2, ..., un such that u = u1, un = v, and (ui, ui + 1) is an edge for all i = 1, 2, ..., n − 1

Connected vertices: there is a path from u to v

Simple path: path in which all vertices, except possibly the first and last, are distinct

Cycle: simple path in which the first and last vertices are the same

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

12

Graph Definitions and Notations (8 of 8)

Connected: path exists from any vertex to any other vertex

Component: maximal subset of connected vertices

In a connected graph G, if there is an edge from u to v, i.e., (u, v)  E(G), then u is adjacent to v and v is adjacent from u

Strongly connected: any two vertices in G are connected

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

13

Graph Representation

To write programs that process and manipulate graphs:

Must store graphs in computer memory

A graph can be represented in several ways:

Adjacency matrices

Adjacency lists

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

14

Adjacency Matrix

G: graph with n vertices (n  0)

V(G) = v1, v2, ..., vn

Adjacency matrix (AG of G): two-dimensional n  n matrix such that:

Adjacency matrix of an undirected graph is symmetric

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Adjacency Lists (1 of 2)

G: graph with n vertices (n  0)

V(G) = v1, v2, ..., vn

Linked list corresponding to each vertex, v,

Each node of linked list contains the vertex, u, such that (u,v)  E(G)

Each node has two components, such as vertex and link

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Adjacency Lists (2 of 2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-5 Adjacency list of graphs of Figure 20-4

‹#›

17

Operations on Graphs (1 of 2)

Operations commonly performed on a graph

Create the graph

Clear the graph

Makes the graph empty

Determine whether the graph is empty

Traverse the graph

Print the graph

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

18

Operations on Graphs (2 of 2)

The adjacency list (linked list) representation

For each vertex, v, vertices adjacent to v are stored in linked list associated with v

In a directed graph, vertices adjacent to v are called immediate successors

To manage data in a linked list, use class unorderedLinkedList

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

19

Graphs as ADTs

We implement graphs as an abstract data type (ADT), including functions to:

Create/clear the graph

Print the graph

Traverse the graph

Determine the graph’s size

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

20

Graph Traversals

Traversing a graph is similar to traversing a binary tree, except that:

A graph might have cycles

Might not be able to traverse the entire graph from a single vertex

Most common graph traversal algorithms

Depth first traversal

Breadth first traversal

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

Depth First Traversal (1 of 2)

Depth first traversal at a given node, v

Mark node v as visited

Visit the node

for each vertex u adjacent to v

if u is not visited

start the depth first traversal at u

This is a recursive algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Depth First Traversal (2 of 2)

Depth-first ordering of vertices:

0, 1, 4, 3, 2, 5, 7, 8, 6, 9

Breadth-first ordering of vertices:

0, 1, 3, 4, 2, 5, 7, 8, 6, 9

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-6 Directed graph G

‹#›

23

Breadth First Traversal

Breadth first traversal of a graph

Similar to traversing a binary tree level by level

Nodes at each level are visited from left to right

Starting at the first vertex, the graph is traversed as much as possible

Then go to next vertex not yet visited

Use a queue to implement the breadth first search algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Shortest Path Algorithm (1 of 9)

Weight of the edge: nonnegative real number assigned to the edges connecting two vertices

Weighted graph: every edge has a nonnegative weight

Weight of the path P

Sum of the weights of all edges on the path P

Also called the weight of v from u via P

Source: starting vertex in the path

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Shortest Path Algorithm (2 of 9)

Shortest path: path with the smallest weight

Shortest path algorithm

Called the greedy algorithm, developed by Dijkstra

G: graph with n vertices, where n ≥ 0

V(G) = {v1, v2, ..., vn}

W: two-dimensional n × n matrix

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Shortest Path Algorithm (3 of 9)

Shortest path algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

For n vertices, repeat Steps 3 through 5, n – 1 times.

‹#›

27

Shortest Path Algorithm (4 of 9)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-7 Weighted graph G

‹#›

28

Shortest Path Algorithm (5 of 9)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-8 Graph after Steps 1 and 2 execute

‹#›

29

Shortest Path Algorithm (6 of 9)

Graph after first iteration of Steps 3, 4, and 5

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-9 Graph after the first iteration of Steps 3 to 5

‹#›

30

Shortest Path Algorithm (7 of 9)

Graph after second iteration of Steps 3, 4, and 5

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-10 Graph after the second iteration of Steps 3 to 5

‹#›

31

Shortest Path Algorithm (8 of 9)

Graph after third iteration of Steps 3, 4, and 5

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-11 Graph after the third iteration of Steps 3 to 5

‹#›

32

Shortest Path Algorithm (9 of 9)

Graph after fourth iteration of Steps 3, 4, and 5

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-12 Graph after the fourth iteration of Steps 3 to 5

‹#›

33

Minimal Spanning Tree (1 of 6)

Company needs to shut down a maximum number of connections and still be able to fly from one city to another

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-13 Airline connections between cities and the cost factor of maintaining the connections

‹#›

34

Minimal Spanning Tree (2 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-14 Possible solutions to the graph of Figure 20-13

‹#›

35

Minimal Spanning Tree (3 of 6)

(Free) tree: simple graph such that if u and v are two vertices in T, then there is a unique path from u to v

Rooted tree: tree in which a particular vertex is designated as a root

Weighted tree: tree in which a weight is assigned to the edges

Weight of T: sum of the weights of all the edges in T, denoted by W(T)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Minimal Spanning Tree (4 of 6)

Spanning tree of graph G: if T is a subgraph of G such that V(T) = V(G)

All the vertices of G are in T

Figure 20-14 shows three spanning trees of the graph shown in Figure 20-13

Theorem: a graph G has a spanning tree if and only if G is connected

Minimal spanning tree: spanning tree in a weighted graph with the minimum weight

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

37

Minimal Spanning Tree (5 of 6)

Two well-known algorithms to find a minimal spanning tree

Kruskal’s algorithm

Prim’s algorithm

Builds the tree iteratively by adding edges until a minimal spanning tree is obtained

Start with a designated vertex, called the source vertex

At each iteration, a new edge that does not complete a cycle is added to the tree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Minimal Spanning Tree (6 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-15 Weighted graph G

‹#›

39

Prim’s Algorithm to Find a Minimal Spanning Tree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 20-16 Prim’s algorithm to find a minimal spanning tree

‹#›

40

Summary (1 of 3)

A graph G is a pair, G = (V, E)

In an undirected graph G = (V, E), the elements of E are unordered pairs

In a directed graph G = (V, E), the elements of E are ordered pairs

H is a subgraph of G if every vertex of H is a vertex of G and every edge is an edge in G

Two vertices in an undirected graph are adjacent if there is an edge between them

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

41

Summary (2 of 3)

Loop: an edge incident on a single vertex

Simple graph: no loops and no parallel edges

Simple path: all the vertices, except possibly the first and last vertices, are distinct

Cycle: a simple path in which the first and last vertices are the same

An undirected graph is connected if there is a path from any vertex to any other vertex

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

42

Summary (3 of 3)

Shortest path algorithm gives the shortest distance for a given node to every other node in the graph

In a weighted graph, every edge has a nonnegative weight

A tree in which a particular vertex is designated as a root is called a rooted tree

A tree T is called a spanning tree of graph G if T is a subgraph of G such that V(T) = V(G)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

43

9781337117562_PPT_ch21.pptx

Chapter 21

Standard Template Library (STL)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

C++ Programming: Program Design Including Data Structures, Eighth Edition

‹#›

1

Objectives (1 of 3)

In this chapter, you will:

Learn about the Standard Template Library (STL)

Become familiar with the three basic components of the STL: containers, iterators, and algorithms

Become familiar with basic operations on vector objects

Learn about the member functions common to all containers

Learn about the member functions common to all sequence containers

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

2

Objectives (2 of 3)

Learn how to use the copy algorithm

Explore how to use range-based for loops

Explore how various containers, such as deque and list, are used to manipulate data in a program

Learn about various types of iterators and how they are used

Explore how to use the associative containers sets, multisets, maps and multimaps

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

3

Objectives (3 of 3)

Explore how to use the container adapters stacks and queues

Become familiar with the various types of STL algorithms

Learn about function objects: arithmetic and relational

Become familiar with insert iterators

Explore how to use various generic algorithms

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

4

Introduction

ANSI/ISO Standard C++ is equipped with a Standard Template Library (STL)

STL includes class templates to process lists, stacks, and queues

This chapter:

Discusses many important features of the STL

Shows how to use its tools

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

5

Components of the STL

Components of the STL

Containers

Iterators

Algorithms

Containers and iterators: class templates

Iterators: used to step through the elements of a container

Algorithms: used to manipulate data

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

6

Container Types

Manage objects of a given type

Three categories

Sequence (sequential) containers

Associative containers

Container adapters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

7

Sequence Containers

Sequence container: every object in the container has a specific position

Three predefined sequence containers

vector

deque

list

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

8

Sequence Container: vector (1 of 6)

Stores and manages its objects in a dynamic array

Must use: #include <vector>

To define an object of type vector, specify the type of the object

Examples:

vector<int> intList;

vector<string> stringList;

vector contains several constructors

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

9

Sequence Container: vector (cont’d.)

Sequence Container: vector (2 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-1 Various Ways to Declare and Initialize a Vector Container

‹#›

10

Sequence Container: vector (3 of 6)

Basic vector operations

Item insertion

Item deletion

Stepping through the elements

Vector elements can be processed just as they can in an array

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

11

Sequence Container: vector (4 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-2 Operations to Access the Elements of a Vector Container

‹#›

12

Sequence Container: vector (5 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-3 Operations to Determine the Size of a Vector Container

‹#›

13

Sequence Container: vector (cont’d.)

Sequence Container: vector (6 of 6)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-4 Various Operations on a Vector Container

‹#›

14

Declaring an iterator to a vector Container

A vector contains a typedef iterator

Examples:

vector<int>::iterator intVecIter;

Declares intVecIter to be an iterator into a vector container of type int

++intVecIter

Advances the iterator

*intVecIter

Returns element at current iterator position

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

15

Containers and the Functions begin and end

Every container contains member functions

begin: returns the position of the first element

end: returns the position of the last element

Both functions have no parameters

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

16

Member Functions Common to All Containers (1 of 3)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-5 Operations Common to All Containers (1 of 3)

‹#›

17

Member Functions Common to All Containers (2 of 3)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-5 Operations Common to All Containers (2 of 3)

‹#›

18

Member Functions Common to All Containers (3 of 3)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-5 Operations Common to All Containers (3 of 3)

‹#›

19

Member Functions Common to Sequence Containers

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-6 Member Functions Common to All Sequence Containers

‹#›

20

The copy Algorithm

Function copy: convenient way to output the elements of a container

Copies elements from one place to another

Can output the elements of a vector

Prototype:

Copies elements within range first1...last-1

Must use: #include <algorithm>

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

21

The ostream Iterator and the Function copy

copy can output a container using an iterator

Iterator of type ostream specifies destination

When creating an iterator of type ostream:

Specify the type of element that the iterator will output

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

22

Sequence Container: deque

deque: double-ended queue

Implemented as dynamic arrays

A deque can expand in either direction

Elements can be inserted at both ends and in the middle

Must use #include <deque>

class deque has several constructors

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

23

Sequence Container: list

List containers are implemented as doubly linked lists

Every element in a list points to immediate predecessor and immediate successor

Except the first and last element

Linked list is not a random access data structure

class list has several constructors

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

24

Iterators

Iterator: points to the elements of a container (sequence or associative)

Provides access to each element

Most common operations on iterators

++ (increment)

* (dereference)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

25

Types of Iterators (1 of 2)

Input iterators:

Have read access; step forward element-by-element

Output iterators:

Have write access; step forward element-by-element

Forward iterators:

Have all functionality of input and almost all of output iterators

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

26

Types of Iterators (2 of 2)

Bidirectional iterators:

Can go backward

Random access iterators:

Bidirectional iterators that can randomly process the elements of a container

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

27

Input Iterators

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-11 Operations on an Input Iterator

‹#›

28

Output Iterators

Output iterators cannot be used to iterate over a range twice

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-12 Operations on an Output Iterator

‹#›

29

Forward Iterators

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-13 Operations on a Forward Iterator

‹#›

30

Bidirectional Iterators

Bidirectional iterator: a forward iterator that can also iterate backward over the elements

The operations defined for forward iterators apply to bidirectional iterators

Use the decrement operator to step backward

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-14 Additional Operations on a Bidirectional Iterator

‹#›

31

Random Access Iterators

Random access iterator: a bidirectional iterator that can randomly process elements of the container

Can be used with containers of the types vector, deque, string, as well as arrays

Operations defined for bidirectional iterators apply to random access iterators

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

FIGURE 21-1 Iterator hierarchy

‹#›

32

typedef iterator

Every container contains a typedef iterator

Used to declare the iterator

Example:

vector<int>::iterator intVecIter;

declares intVecIter to be an iterator into a vector container of the type int

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

33

typedef const_iterator

Use an iterator and the dereference operator, *, to modify the elements of the container

Every container also contains typedef const_iterator to prevent the iterator from modifying the elements of a const container

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

34

typedef reverse_iterator

Every container also contains the typedef reverse_iterator

Used to iterate through the elements of a container in reverse

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

35

typedef const_reverse_iterator

Read-only iterator

Used to iterate through the elements of a container in reverse

Required if the container is declared as const, and iteration through the elements of the container in reverse is needed

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

36

Stream Iterators

istream_iterator

Used to input data into a program from an input stream

ostream_iterator

Used to output data into an output stream

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

or

‹#›

37

Associative Containers

Associative container: stores elements automatically sorted according to some ordering criteria

Default criteria: < (less than)

Predefined associative containers in the STL

Sets

Multisets

Maps

Multimaps

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

38

Associative Containers: set and multiset

Associative containers set and multiset automatically sort elements in ascending order

multiset allows duplicates; set does not

Default sorting criterion is < (less than)

Ascending order

Must use #include <set>

See Tables 21-17 and 21-18 in text

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

39

Container Adapters

Container adapters: containers to accommodate special situations

Three container adapters

Stacks

Queues

Priority Queues

Do not support any type of iterator

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

40

Stack

The STL provides a stack class

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-19 Various Operations on a stack Object

‹#›

41

Queue

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-20 Various Operations on a queue Object

‹#›

42

Containers, Associated Header Files, and Iterator Support (1 of 2)

Every container is a class

Definition of the class implementing a specific container is contained in the header file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

43

Containers, Associated Header Files, and Iterator Support (2 of 2)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-21 Containers, Their Associated Header Files, and the Type of Iterator Supported by Each Container

‹#›

44

Algorithms

Several operations can be defined for a container

Some are very specific to a container – provided as part of the container definition

Other operations are common to all containers

Generic algorithms contained in the header file algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

45

STL Algorithm Classification

Operations such as clear, sort, and merge are common to all containers

Provided as generic algorithms

STL algorithm classifications

Nonmodifying algorithms

Modifying algorithms

Numeric algorithms

Heap algorithms

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

46

Nonmodifying Algorithms

Nonmodifying algorithms: do not modify the elements of the container

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-22 Nonmodifying Algorithms

‹#›

47

Modifying Algorithms

Modifying algorithms: modify the elements of the container

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-23 Modifying Algorithms

‹#›

48

Numeric Algorithms

Perform numeric calculations on elements of a container

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-24 Numeric Algorithms

‹#›

49

Heap Algorithms

Heap sort algorithm sorts array data

Array containing the data is viewed as a binary tree

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

TABLE 21-25 Heap Algorithms

‹#›

50

Function Objects (1 of 2)

To make a generic algorithm flexible, the STL usually provides two forms

Use the natural operation to accomplish the goal

Specify criteria based on which algorithm processes the elements

Criteria are passed as a function object

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

51

Function Objects (2 of 2)

Function object: contains a function that can be treated as such using the operator()

Class template that overloads the function call operator

STL provides arithmetic, relational, and logical function objects

Contained in the header file functional

See Tables 21-26 through 21-28 in the text

Can also create your own

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

52

Predicates

Predicates: special types of function objects that return Boolean values

Two types

Unary: check a property for a single argument

Binary: check a specific property for a pair

Predicate must always return the same result for the same value

Functions that modify their internal states cannot be considered predicates

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

53

Insert Iterator

STL provides 3 insert iterators to insert elements at the desired destination

back_inserter: uses push_back in place of = operator; the argument is the container

front_inserter: uses push_front; argument is the container itself

Cannot be used for the vector container

inserter: uses insert operation; must pass container and an iterator specifying the position at which the insertion should begin

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

54

STL Algorithms

STL algorithms include documentation with the function prototypes

The parameter types indicate for which type of container the algorithm is applicable

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

55

The Functions fill and fill_n

Fill functions

fill: fills a container with elements

fill_n: fills in the next n elements

filling element is passed as a parameter

Defined in header file algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

56

The Functions generate and generate_n

Generate functions

generate: fills a sequence

generate_n: fills a sequence in a range

Defined in header file algorithm

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

57

The Functions find, find_if, find_end, and find_first_of

Find functions

find: searches for searchValue

find_if: searched for element for which op(rangeElement) is true

find_end: searches for last occurrence

find_first_of: searches for first occurrence

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

58

The Functions remove, remove_if, remove_copy, and remove_copy_if

Remove functions

remove: removes certain elements from a sequence

remove_if: removes elements from a sequence by using some criteria

remove_copy: copies all elements except those specified by value

remove_copy_if: copies all elements except those for which op(element) is true

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

59

The Functions replace, replace_if, replace_copy, and replace_copy_if

Replace and copy functions

replace: replaces all occurrences with given range

replace_if: replaces all occurrences with given range satisfying some criteria

replace_copy: combination of replace and copy

replace_copy_if: combination of replace_if and copy_if

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

60

Swap functions

swap: swaps values of object1 and object2

iter_swap: swaps values to which iterators first and second point

swap_ranges: swaps one range of elements with another range of elements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

The Functions swap, iter_swap, and swap_ranges

‹#›

61

The Functions search, search_n, sort, and binary_search

Search and sort functions

search: searches for a subrange

search_n: searches count consecutive occurrences of value

sort: reorders elements in a range in ascending order

binary_search: returns true if searchValue is found in the range

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

62

The Functions adjacent_find, merge, and inplace_merge

adjacent_find: finds the first occurrence of consecutive elements that meet criteria

merge: merges sorted lists

inplace_merge: combines sorted consecutive sequences

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

63

The Functions reverse, reverse_copy, rotate, and rotate_copy

Reverse and rotate functions

reverse: reverses element order in given range

reverse_copy: reverses elements of a given range while copying into a destination range; the source is not modified

rotate: rotates elements of a given range

rotate_copy: combination of rotate and copy; elements of the source are copied at the destination in a rotated order

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

64

The Functions count, count_if, max, max_element, min, min_element, and random_shuffle (1 of 2)

Count functions

count: counts occurrence of a given item in a given range

count_if: counts occurrences of a given value in a given range satisfying a certain criterion

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

65

The Functions count, count_if, max, max_element, min, min_element, and random_shuffle (2 of 2)

Min/Max functions

min: determines the minimum of two values

max: determines the maximum of two values

max_element: determines the largest element in a given range

min_element: determines the smallest element in a given range

Shuffle function

random_shuffle: randomly orders elements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

66

The Functions for_each and transform

for_each: accesses and processes each element in a given range by applying a function

transform: creates a sequence of elements at the destination by applying the unary operation to each element in the range

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

67

The Functions includes, set_intersection, set_union, set_difference, and set_symmetric_difference

Set functions

includes: determines if elements in one range appear in another range

set_intersection: finds elements that are common to two ranges

set_union: finds elements that are contained in two ranges of elements

set_difference: finds elements in one range that are not in the other range

set_symmetric_difference: creates a sequence of sorted elements that are in one range but not the other, in both directions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

68

The Functions accumulate, adjacent_difference, inner_product, and partial_sum

Numerical functions

accumulate: finds the sum of all elements in a given range

adjacent_difference: creates a sequence in which the first element is the same, and all other elements are the differences of the current and previous elements

inner_product: multiplies corresponding elements of two ranges

partial_sum: creates a sequence in which each element is the sum of all previous elements in the range

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

69

Summary (1 of 2)

STL consists of

Containers: class templates

Iterators: step through the elements of a container

Algorithms: manipulate the elements in a container

Containers

Sequence: vector, deque, and list

Associative: sets, multisets, maps, and multimaps

Container adapters: stacks, queues, and priority queues

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

70

Summary (2 of 2)

Iterators: input, output, forward, bidirectional, and random access iterator

Predicates: Boolean function objects

Algorithms: nonmodifying, modifying, numerical, and heap

Algorithms are overloaded for flexibility

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom

‹#›

71