Document Sample
C++ Powered By Docstoc
   C/C++ 程式設計

   E-mail: yen@ee.ntu.edu.tw
•學歷        博士 Univ. of Texas at Austin (電腦) 1986
           碩士 交大計算機工程研究所                 1982
           學士 台大電機系                      1980

•經歷        台大電機系 教授               1991 -- present
           台大電機系 副教授              1990 -- 1991
           美國Iowa State Univ.電腦系助理教授   1986-1990

•專長        資料結構, 演算法, 計算理論, 通訊協定工程
 slide 2
                 Life Cycle of Software Development
                    Probl em
                                            S pecifi cati on
                                                                  Form al
                 Interpre tation                                 Description

          appropri ate a ssu mpti ons
                                                                            Abstracti on
                                           D ata structures    M odeli ng and
desi gn             Al gorithm
                                                               Anal ysis o f the
techni ques          Desi gn
                                                               Probl em

                                                               Problem rep resent at ion,
                                                               p rop ert ies of t he p roblem
compl exi ty;     Al gorithm                 N ot satisfi ed
correctness       Anal ysi s

                            S a ti sfied                             D ON E

                                                                            O .K.

                   Al gorithm                                      Program
                 Impl em entatio n                                Verifi ca ti on
                                              N ot O .K.
      slide 3
                Fai thful codi ng                              Parti al correctness,
                                                               Te rmi nati on
           Chapter 1
Introduction to Computers and
1.1 Why Program?
1.2 Computer Systems: Hardware and Software
1.3 Programs and Programming Languages
1.4 What Is a Program Made of?
1.5 Input, Processing, and Output
1.6 The Programming Process
1.7 Procedural and Object-Oriented Programming
 slide 5
           1.1 Why Program?
Computer – programmable machine designed to
  follow instructions
Program – instructions in computer memory to make it
  do something
Programmer – person who writes instructions
  (programs) to make computer perform a task

SO, without programmers, no programs; without
 programs, computer cannot do anything
slide 6
1.2 Computer Systems: Hardware
        and Software
Main Hardware Component Categories:

      1.   Central Processing Unit (CPU)
      2.   Main Memory
      3.   Secondary Memory / Storage
      4.   Input Devices
      5.   Output Devices

slide 7
          Main Hardware Component
            Input                            Output
           Device                            Device


slide 8
      Central Processing Unit (CPU)
Comprised of:
      Control Unit
          Retrieves and decodes program instructions
          Coordinates activities of all other parts of computer
      Arithmetic & Logic Unit
          Hardware optimized for high-speed numeric calculation
          Hardware designed for true/false, yes/no decisions

slide 9
                   Main Memory
• Volatile – erased when program terminates or
  computer is turned off
• Also called Random Access Memory (RAM)
• Organized as follows:
  – bit: smallest piece of memory. Has values 0 (off, false)
    or 1 (on, true)
  – byte: 8 consecutive bits. Bytes have addresses.

  slide 10
               Secondary Storage
• Non-volatile: data retained when program is
  not running or computer is turned off
• Comes in a variety of media:
      – magnetic: floppy disk, zip disk, hard drive
      – optical: CD-ROM

slide 11
                 Input Devices
• Used to send information to computer from
• Many devices can provide input:
     – Keyboard, mouse, scanner, camera
     – Disk drives

slide 12
                Output Devices
• Used for information sent from a computer
• Many devices can be used for output:
     – Computer monitor and printer
     – Floppy, zip disk drives
     – Writable CD drives

slide 13
Software – Programs That Run on
           a Computer
• Categories of software:
     – Operating system: programs that manage the
       computer hardware and the programs that run on
       them. Ex: Windows, UNIX, Linux
     – Application software: programs that provide
       services to the user. Ex: word processing,
       games, programs to solve specific problems

slide 14
   1.3 Programs and Programming
• Program: a set of instructions to a computer
  to perform a task

• Programming Language: a language used to
  write programs

slide 15
                Programs and
           Programming Languages
• Types of languages:

     – Low-level: used for communication with computer
       hardware directly. Often written in binary
       machine code (0’s/1’s) directly.

     – High-level: closer to human language

slide 16
      From a High-level Program to an
              Executable File
a)       Create file containing the program with a text editor.
b)       Run preprocessor to convert source file directives to source
         code program statements.
c)       Run compiler to convert source program into machine
d)       Run linker to connect hardware-specific code to machine
         instructions, producing an executable file.
-        Steps b–d are often performed by a single command or button
-        Errors detected at any step will prevent execution of following
    slide 17
  From a High-level Program to an
          Executable File
     Source Code      Object Code

     Preprocessor        Linker

        Modified     Executable Code
      Source Code


slide 18
  1.4 What Is a Program Made Of?
• Common elements in programming
     – Key Words
     – Programmer-Defined Symbols
     – Operators
     – Punctuation
     – Syntax

slide 19
           Example Program
#include <iostream>
#include <string>
using namespace std;
int main()
  string name;
  cout << "What is your name? ";
  cin >> name;
  cout << "Hello there, " << name;
  return 0;
slide 20
               Key Words
•   Also known as reserved words
•   Have a special meaning in C++
•   Can not be used for another purpose
•   Examples in program: using, namespace,
    int, main

slide 21
      Programmer-Defined Symbols
• Names made up by the programmer
• Not part of the C++ language
• Used to represent various things: variables
  (memory locations), functions, etc.
• Example in program: name

slide 22
• Used to perform operations on data
• Many types of operators:
     – Arithmetic - ex: +,-,*,/
     – Assignment – ex: =

• Examples in program: <<, >>

slide 23
• Characters that mark the end of a statement,
  or that separate items in a list
• Examples in program: ;

slide 24
• The rules of grammar that must be followed
  when writing a program
• Controls the use of key words, operators,
  programmer-defined symbols, and

slide 25
 1.5 Input, Processing, and Output
Three steps many programs perform:
     1) Gather input data:
           -   from keyboard
           -   from files on disk drives
     2) Process the input data
     3) Display the results as output:
           -   send it to the screen
           -   write to a file

slide 26
      1.6 The Programming Process
1. Define the purpose of the program
2. Visualize the running program; sketch the
   user interface
3. Model the program using design tools
4. Check the model for errors
5. Enter the program into the computer and
   compile it
slide 27
           The Programming Process
6. Correct errors and recompile until there are
7. Execute (run) the program
8. Correct execution errors, recompile, rerun
9. Validate results: does the output meet what
   was defined in step 1?

slide 28
           1.7 Procedural and Object-
             Oriented Programming
• Procedural programming: focus is on the
  process. Procedures/functions are written to
  process data.
• Object-Oriented programming: focus is on
  objects, which contain data and the means to
  manipulate the data. Messages sent to
  objects to perform operations.

slide 29
     Chapter 2
Introduction to C++
2.1 Parts of a C++ Program
2.2 The cout Object
2.3 The #include Directive
2.4 Variables and Constants
2.5 Identifiers
2.6 Integer Data Types
2.7 The char Data Type
2.8 Floating-Point Data Types
slide 31
            Topics (continued)
2.9 The bool Data Type
2.10 Determining the Size of a Data Type
2.11 Variable Assignments and Initialization
2.12 Scope
2.13 Arithmetic Operators
2.15 Programming Style
2.16 Standard and Prestandard C++
slide 32
           2.1 Parts of a C++ Program
// sample C++ program                          preprocessor
#include <iostream>
                                               which namespace
using namespace std;                                to use
int main()                beginning of
                      function named main
{        beginning of
       block for main
    cout << "Hello, there!";                          output
    return 0;                                   string
}       end of block
                                send 0 to
               for main
                            operating system

slide 33
               Special Characters
   Character    Name                   Meaning
   //           Double slash           Beginning of a comment
   #            Pound sign             Beginning of preprocessor
   < >          Open/close brackets    Enclose filename in #include
   ( )          Open/close             Used when naming a function
   { }          Open/close brace       Encloses a group of statements

   " "          Open/close quotation   Encloses string of characters
   ;            Semicolon              End of a programming
slide 34
            2.2 The cout Object
• Displays information on computer screen
• Uses << to send information to cout:
       cout << "Hello, there!";
• Can be used to send > 1 item to cout:
    cout << "Hello, " << "there!";
       cout << "Hello, ";
      cout << "there!";
 slide 35
             The cout Object
• To get multiple lines of output on screen:
   - Use endl
      cout << "Hello, there!" << endl;
   - Use \n in output string
      cout << "Hello, there!\n";

 slide 36
           2.3 The #include Directive
• Inserts the contents of another file into the
• Preprocessor directive, not part of C++
• #include lines not seen by compiler
• Do not use ; at end of #include line

slide 37
           2.4 Variables and Constants
• Variable: storage location in memory Not the
  same meaning as in Math!
     – Has a name and a type of data it can hold
     – Must be defined before it can be used:
       int item;
• Constant: item whose value does not change
  during program execution
           "hello, there" (string constant)
           12 (integer constant)

slide 38
               2.5 Identifiers
• Programmer-chosen names to represent parts
  of the program: variables, functions, etc.
• Name should represent the use of the variable
• Cannot use C++ key words as identifiers
• Must begin with alpha character or _, followed
  by alpha, numeric, or _
• Upper- and lower-case characters are distinct
 slide 39
            Valid and Invalid Identifiers
totalSales          Yes

total_Sales         Yes

total.Sales         No       Cannot contain .

4thQtrSales         No       Cannot begin with digit

totalSale$          No       Cannot contain $

 slide 40
             2.6 Integer Data Types
• Designed to hold whole numbers
• Can be signed or unsigned:
  – 12        -6     +3
• Available in different sizes (number of bytes):
  short, int, and long
• Size of short  size of int  size of long

  slide 41
             Defining Variables
• Variables of the same type can be defined
     - On separate lines:
       int length;
       int width;
       unsigned int area;
     - On the same line:
       int length, width;
       unsigned int area;
• Variables of different types must be in different

slide 42
           Integral Constants
• Integer constants stored in as ints by default
• To store an integer constant in a long memory
  location, put ‘L’ at the end of the number:
• Constants that begin with ‘0’ (zero) are base 8:
• Constants that begin with ‘0x’ are base 16:
slide 43
           2.7 The char Data Type
• Used to hold characters or very small integer
• Usually 1 byte of memory
• Numeric value of character from character
  set is stored in memory:
    CODE:                  MEMORY:
    char letter;          letter
    letter = 'C';            67

slide 44
                 Character Strings
• Can store a series of characters in
  consecutive memory locations:
• Stored with the null terminator, \0, at the end:

     H    e    the l  o \0
• Comprised of l characters between the "

slide 45
        2.8 Floating-Point Data Types
• Designed to hold real numbers
      12.45      -3.8
• Stored in a form similar to scientific notation
• All numbers are signed
• Available in different sizes (number of bytes):
  float, double, and long double
• Size of float  size of double
                    size of long double
  slide 46
           Floating-point Constants
• Can be represented in
     - Fixed point (decimal) notation:
       31.4159                 0.0000625
     - E notation:
       3.14159E1               6.25e-5
• Are double by default
• Can be forced to be float (3.14159f) or long
  double (0.0000625L)
slide 47
            2.9 The bool Data Type
• Represents values that are true or false
• bool variables are stored as small integers
• false is represented by 0, true by 1:
       bool allDone = true;
                                    allDone   finished
       bool finished = false;         1          0

 slide 48
       2.10 Determining the Size of a
                Data Type
The sizeof operator gives the size of any data type or
float amount;
cout << "A float is stored in "
      << sizeof(float) << "bytes\n";
cout << "Variable amount is stored in "
      << sizeof(amount)
       << "bytes\n";
 slide 49
     2.11 Variable Assignments and
• Uses the = operator
• Has a single variable on the left side and a
  value (constant, variable, or expression) on
  the right side
• Copies the value on the right into the variable
  on the left:
  item = 12;
slide 50
             Variable Assignments and
• Initialize a variable: assign it a value when it is
       int length = 12;
• Can initialize some or all variables:
       int length = 12, width = 5, area;

  slide 51
                2.12 Scope
• The scope of a variable: where the program
  can access the variable
• A variable cannot be used before it is defined

slide 52
            2.13 Arithmetic Operators
• Used for performing numeric calculations
• C++ has unary, binary, and trinary operators:
  – unary (1 operand)        -5
  – binary (2 operands)   13 - 7
  – ternary (3 operands) exp1 ? exp2 : exp3

 slide 53
            Binary Arithmetic Operators
   +         addition         ans = 7 + 3;     10

   -         subtraction      ans = 7 - 3;      4

   *         multiplication   ans = 7 * 3;     21

   /         division         ans = 7 / 3;      2

   %         modulus          ans = 7 % 3;      1

 slide 54
                    / Operator
• / (division) operator performs integer division if
  both operands are integers
   cout << 13 / 5;         // displays 2
   cout << 91 / 7;         // displays 13
• If either operand is floating point, the result is
  floating point
   cout << 13 / 5.0;       // displays 2.6
   cout << 91.0 / 7;       // displays 13.0

  slide 55
                   % Operator
• % (modulus) operator computes the remainder
  resulting from integer division
  cout << 13 % 5;      // displays 3
• % requires integers for both operands
  cout << 13 % 5.0; // error

 slide 56
• Used to document parts of the program
• Intended for persons reading the source code
  of the program:
     – Indicate the purpose of the program
     – Describe the use of variables
     – Explain complex sections of code
• Are ignored by the compiler

slide 57
           C++ Style Comments
Begin with // through to the end of line:
int length = 12; // length in inches
int width = 15; // width in inches
int area;        // calculated area

// calculate rectangle area
area = length * width;

slide 58
           C-Style Comments
• Begin with /*, end with */
• Can span multiple lines:
     /* this is a multi-line
        C-style comment
• Can be used like C++ style comments:
     int area;   /* calculated area */

slide 59
           2.15 Programming Style
• The visual organization of the source code
• Includes the use of spaces, tabs, and blank
• Does not affect the syntax of the program
• Affects the readability of the source code

slide 60
           Programming Style
Common elements to improve readability:
• Braces { } aligned vertically
• Indentation of statements within a set of
• Blank lines between declaration and other
• Long statements wrapped over multiple lines
  with aligned operators
slide 61
    2.16 Standard and Prestandard
Older-style C++ programs:
     • Use .h at end of header files:
       #include <iostream.h>
     • Do not use using namespace convention
     • May not compile with a standard C++ compiler

slide 62
         Chapter 3
Expressions and Interactivity
3.1 The cin Object
3.2 Mathematical Expressions
3.3 When You Mix Apples and Oranges: Type
3.4 Overflow and Underflow
3.5 Type Casting
3.6 Named Constants
slide 64
           Topics (continued)
3.7 Multiple Assignment and Combined Assignment
3.8 Formatting Output
3.9 Formatted Input
3.10 More About Member Functions
3.11 More Mathematical Library Functions
3.12 Hand Tracing a Program
3.14 Introduction to File Input and Output

slide 65
           3.1 The cin Object
• Standard input object
• Like cout, requires iostream file
• Used to read input from keyboard
• Often used with cout to display a user
  prompt first
• Information retrieved from cin with >>
• Input information stored in one or more
slide 66
               The cin Object
• User input goes from keyboard to keyboard
• cin converts information to the type that
  matches the variable:
      int height;
      cout << "How tall is the room? ";
      cin >> height;

 slide 67
               The cin Object
• Can be used to input > 1 value:
      cin >> height >> width;
• Multiple values from keyboard must be
  separated by spaces
• Order is important: first value entered goes to
  first variable, etc.

 slide 68
                 The cin Object
• Can be used to read in a string
• Must first declare an array to hold characters in string:
       char myName[20];
• nyName is name of array, 20 is the number of
  characters that can be stored (the size of the array),
  including the NULL character at the end
• Can be used with cin to assign a value:
       cin >> myName;

  slide 69
        3.2 Mathematical Expressions
• Can create complex expressions using
  multiple mathematical operators
• An expression can be a constant, a variable, or
  a mathematical combination of constants and
• Can be used in assignment, cout, other
       area = 2 * PI * radius;
       cout << "border is: " << 2*(l+w);

 slide 70
               Order of Operations
 In an expression with > 1 operator, evaluate in
 this order:
      - (unary negation), in order, left to right
      * / %, in order, left to right
      + -, in order, left to right
 In the expression 2 + 2 * 2 – 2 ,
                         evaluate     evaluate      evaluate
                         second         first         third

slide 71
                Associativity of Operators
• - (unary negation) associates right to left
• *, /, %, +, - associate right to left
• parentheses ( ) can be used to override the
  order of operations:
   2        +   2    * 2 –    2    =   4
  (2        +   2)   * 2 –    2    =   6
   2        +   2    * (2 –   2)   =   2
  (2        +   2)   * (2 –   2)   =   0

 slide 72
                 Algebraic Expressions
• Multiplication requires an operator:
      Area=lw is written as Area = l * w;
• There is no exponentiation operator:
      Area=s2 is written as Area = pow(s, 2);
• Parentheses may be needed to maintain order of
                           is written as
                y 2  y1
             m            m = (y2-y1) /(x2-x1);
                x 2  x1
  slide 73
      3.3 When You Mix Apples and
        Oranges: Type Conversion
• Operations are performed between operands
  of the same type.
• If not of the same type, C++ will convert one
  to be the type of the other
• This can impact the results of calculations.

slide 74
           Hierarchy of Types
Highest:    long double
            unsigned long
            unsigned int
Lowest:     int
Ranked by largest number they can hold
slide 75
             Type Coercion
• Type Coercion: automatic conversion of an
  operand to another data type
• Promotion: convert to a higher type
• Demotion: convert to a lower type

slide 76
             Coercion Rules
1) char, short, unsigned short
   automatically promoted to int
2) When operating on values of different data
   types, the lower one is promoted to the type
   of the higher one.
3) When using the = operator, the type of
   expression on right will be converted to type
   of variable on left

slide 77
           3.4 Overflow and Underflow
• Occurs when assigning a value that is too
  large (overflow) or too small (underflow) to be
  held in a variable
• Variable contains value that is ‘wrapped
  around’ set of possible values
• Different systems may display a
  warning/error message, stop the program, or
  continue execution using the incorrect value

slide 78
              3.5 Type Casting
• Used for manual data type conversion
• Useful for floating point division using ints: float
  m = static_cast<float>(y2-y1)
• Useful to see int value of a char variable:
  char ch = 'C';
  cout << ch << " is "
       << static_cast<int>(ch);
  slide 79
      C-Style and Prestandard Type
            Cast Expressions
• C-Style cast: data type name in ()
           cout << ch << " is " << (int)ch;
• Prestandard C++ cast: value in ()
       cout << ch << " is " << int(ch);
• Both are still supported in C++, although
  static_cast is preferred

slide 80
              3.6 Named Constants
• Named constant (constant variable): variable
  whose content cannot be changed during
  program execution
• Used for representing constant values with
  descriptive names:
           const float TAXRATE = 0.0675;
           const int NUMSTATES = 50;
• Often named in uppercase letters
slide 81
            const vs. #define
• #define – C-style of naming constants:
       #define NUMSTATES 50
   – Note no ; at end
• Interpreted by pre-processor rather than
• Does not occupy memory location like const

 slide 82
           3.7 Multiple Assignment and
              Combined Assignment
• = is an operator that can be used > 1 time in
  an expression:
           x = y = z = 5;
• Value of = is the value that is assigned
• Associates right to left:
           x = (y = (z = 5));
             value   value   value
              is 5    is 5    is 5
slide 83
            Combined Assignment
• C++ shorthand for common mathematical
       sum = sum + newnum;
   – Note: not an algebraic equation!
• Operators: +=, -=, *=, /=, %=
• sum += newnum; short for expression above

 slide 84
            3.8 Formatting Output
• Can control how output displays for numeric,
  string data:
     – size
     – position
     – number of digits
• Requires iomanip header file

slide 85
               Stream Manipulators
• Used to control features of an output field
• Some affect just the next value displayed:
  – setw(x): print in a field at least x spaces wide. Use more
    spaces if field is not wide enough
• Some affect values until changed again:
  – fixed: use decimal notation for floating-point values
  – setprecision(x): when used with fixed, print floating-
    point value using x digits after the decimal. Without fixed,
    print floating-point value using x significant digits
  – showpoint: always print decimal for floating-point values

   slide 86
             Manipulator Examples
const float e = 2.718;
cout << setw(8) << e;   // 2.718 in a
                        // field 8 wide
cout << setprecision(2);
cout << e;             // 2.7
float price = 25.0, discount = 0.6;
cout << fixed << setprecision(2);
cout << price * discount; // 18.00
  slide 87
               3.9 Formatted Input
• Can format field width for use with cin
• Useful when reading string data to be stored
  in a character array:
           char fName[10];
           cout << "Enter your name: ";
           cin >> setw(10) >> fName;
• cin reads one less character than specified
  in setw() directive
slide 88
                  Formatted Input
• To read an entire line of input, use
           char address[81];
           cout << "Enter your address: ";
           cin.getline(address, 81);
• cin.getline takes two arguments:
     – Name of array to store string
     – Size of the array

slide 89
                    Formatted Input
• To read a single character:
  – Use cin:
       char ch;
       cout << "Strike any key to continue";
       cin >> ch;
       Problem: will skip over blanks, tabs, <CR>
  – Use cin.get():
       Will read the next character entered, even whitespace

  slide 90
                Formatted Input
• Mixing cin and cin.get() in the same program can
  cause input errors that are hard to detect
• To skip over unneeded characters that are still in the
  keyboard buffer, use cin.ignore():
       cin.ignore(); // skip next char
       cin.ignore(10, '\n'); // skip the next
                   // 10 char. or until a '\n'

 slide 91
            3.10 More About Member
• Member Function: procedure that is part of an
• cout, cin are objects
• Some member functions of the cin object:
  – getline
  – get
  – ignore

 slide 92
    3.11 More Mathematical Library
• Require cmath header file
• Take double as input, return a double
• Commonly used functions:
           sin    Sine
           cos    Cosine
           tan    Tangent
           sqrt   Square root
           log    Natural (e) log
           abs    Absolute value (takes and returns an
slide 93
           More Mathematical Library
• These require cstdlib header file
• rand(): returns a random number (int)
  between 0 and the largest int the compute
  holds. Yields same sequence of numbers
  each time program is run.
• srand(x): initializes random number
  generator with unsigned int x

slide 94
       3.12 Hand Tracing a Program
• Hand trace a program: act as if you are the
  computer, executing a program:
     – step through and ‘execute’ each statement, one-
     – record the contents of variables after statement
       execution, using a hand trace chart (table)
• Useful to locate logic or mathematical errors

slide 95
 3.14 Introduction to File Input and
• Can use files instead of keyboard, monitor
  screen for program input, output
• Allows data to be retained between program
• Steps:
     – Open the file
     – Use the file (read from, write to, or both)
     – Close the file

slide 96
                Files: What is Needed
• Use fstream header file for file access
• File stream types:
           ifstream for input from a file
           ofstream for output to a file
           fstream for input from or output to a file
• Define file stream objects:
           ifstream infile;
           ofstream outfile;
slide 97
                    Opening Files
• Create a link between file name (outside the
  program) and file stream object (inside the program)
• Use the open member function:
• Filename may include drive, path info.
• Output file will be created if necessary; existing file
  will be erased first
• Input file must exist for open to work
slide 98
                  Using Files
• Can use output file object and << to send data to
  a file:
      outfile << "Inventory report";
• Can use input file object and >> to copy data
  from file to variables:
      infile >> partNum;
      infile >> qtyInStock >> qtyOnOrder;

 slide 99
                     Closing Files
• Use the close member function:
• Don’t wait for operating system to close files
  at program end:
     – may be limit on number of open files
     – may be buffered output data waiting to send to

slide 100
   Chapter 4
Making Decisions
4.1 Relational Operators
4.2 The if Statement
4.3 Flags
4.4 Expanding the if Statement
4.5 The if/else Statement
4.6 The if/else if Statement
4.7 Using a Trailing else
4.8 Menus
4.9 Nested if Statements
slide 102
4.10 Logical Operators
4.11 Checking Numeric Ranges with Logical Operators
4.12 Validating User Input
4.13 More About Variable Definitions and Scope
4.14 Comparing Strings
4.15 The Conditional Operator
4.16 The switch Statement
4.17 Testing for File Open Errors
slide 103
             4.1 Relational Operators
• Used to compare numbers to determine
  relative order
• Operators:
            >    Greater than
            <    Less than
            >=   Greater than or equal to
            <=   Less than or equal to
            ==   Equal to
            !=   Not equal to
slide 104
               Relational Expressions
• Boolean expressions – true or false
• Examples:
            12 > 5 is true
            7 <= 5 is false
            if x is 10, then
            x == 10 is true,
            x != 8 is true, and
            x == 8 is false

slide 105
               Relational Expressions
• Can be assigned to a variable:
            result = x <= y;
• Assigns 0 for false, 1 for true
• Do not confuse = and ==

slide 106
               4.2 The if Statement
• Allows statements to be conditionally
  executed or skipped over
• Models the way we mentally evaluate
     – “If it is raining, take an umbrella.”
• Format:
            if (expression)

slide 107
       if statement – what happens
To evaluate:
     if (expression)
• If (expression) is true, then statement
  is executed.
• If (expression) is false, then
  statement is skipped.

slide 108
       if statement – what happens


            expression                expression
              is true                   is false


slide 109
                 if statement notes
• Do not place ; after (expression)
• Place statement; on a separate line after
  (expression), indented:
            if (score > 90)
                grade = 'A';
• Don’t test floats for equality
• 0 is false; any other value is true
slide 110
                  4.3 Flags
• Variable that signals a condition
• Often implemented as bool
• As with other variables in functions, must be
  assigned an initial value before it is used

slide 111
   4.4 Expanding the if Statement
• To execute > 1 statement as part of an if
  statement, enclose them in { }:
            if (score > 90)
                 grade = 'A';
                 cout << "Good Job!\n";
• { } creates a block of code
slide 112
            4.5 The if/else Statement
• Allows choice between statements if
  (expression) is true or false
• Format:
            if (expression)
                 statement1;   // or block
                 statement2;   // or block

slide 113
             if/else – what happens
To evaluate:
        if (expression)
• If (expression) is true, then statement1 is
  executed and statement2 is skipped.
• If (expression) is false, then statement1 is
  skipped and statement2 is executed.

 slide 114
             if/else – what happens


            expression                expression
              is true                   is false



slide 115
  4.6 The if/else if Statement
• Chain of if statements that test in order until
  one is found to be true
• Also models thought processes:
     – “If it is raining, take an umbrella,   else, if
       it is windy, take a hat, else,
         take sunglasses”

slide 116
            if/else if format
     if (expression)
          statement1; // or block
     else if (expression)
          statement2; // or block
         . // other else ifs        .
     else if (expression)
          statementn; // or block

slide 117
            4.7 Using a Trailing else
• Used with if/else if statement when
  none of (expression) is true
• Provides default statement/action
• Used to catch invalid values, other
  exceptional situations

slide 118
                 4.8 Menus
• Menu-driven program: program execution
  controlled by user selecting from a list of
• Menu: list of choices on the screen
• Can be implemented using if/else if

slide 119
Menu-driven program organization
• Display list of numbered or lettered choices
  for actions
• Prompt user to make selection
• Test user selection in (expression)
     – if a match, then execute code for action
     – if not, then go on to next (expression)

slide 120
             4.9 Nested if Statements
• An if statement that is part of the if or else part
  of another if statement
• Can be used to evaluate > 1 data item or condition:
            if (score < 100)
                if (score > 90)
                    grade = 'A';

slide 121
            Notes on coding nested ifs
• An else matches the nearest if that
  does not have an else:
            if (score < 100)
                if (score > 90)
                   grade = 'A';
                else ...// goes with second if,
                        // not first one
• Proper indentation helps greatly
slide 122
            4.10 Logical Operators
• Used to create relational expressions from
  other relational expressions
• Operators, meaning, and explanation:
    &&      AND   New relational expression is true if both
                  expressions are true
    ||      OR    New relational expression is true if either
                  expression is true
    !       NOT   Reverses the value of an expression – true
                  expression becomes false, and false
                  becomes true
slide 123
       Logical Operators - examples
      int x = 12, y = 5, z = -4;

     (x > y) && (y > z)            true
     (x > y) && (z > y)            false
     (x <= z) || (y == z)          false
     (x <= z) || (y != z)          true
     !(x >= z)                     false

slide 124
            Logical Operators - notes
• ! has highest precedence, followed by &&,
  then ||
• If the value of an expression can be
  determined by evaluating just the sub-
  expression on left side of a logical operator,
  then the sub-expression on the right side will
  not be evaluated (short circuit evaluation)

slide 125
   4.11 Checking Numeric Ranges
        with Logical Operators
• Used to test to see if a value falls into a range:
        if (grade >= 0 && grade <= 100)
           cout << "Valid grade";
• Can also test to see if value falls outside of range:
         if (grade <= 0 || grade >= 100)
            cout << "Invalid grade";
• Cannot use mathematical notation:
        if (0 <= grade <= 100) //doesn’t work!

 slide 126
            4.12 Validating User Input
• Input validation: inspecting data to a program
  to determine if it is acceptable
• Bad output will be produced from bad input
• Can perform various tests:
     – Range
     – Reasonableness
     – Valid menu choice
     – Divide by zero

slide 127
            4.13 More About Variable
              Definitions and Scope
• Scope of a variable is the block in which it is
  defined, from the point of definition to the end
  of the block
• Usually defined at beginning of function
• May be defined close to first use

slide 128
            Still More About Variable
             Definitions and Scope
• Variables defined inside { } have local or
  block scope
• When inside a block within another block, can
  define variables with the same name as in the
  outer block.
     – When in inner block, outer definition is not
     – Not a good idea
slide 129
            4.14 Comparing Strings
• Can not use relational operators with
  character strings
• Must use the strcmp function to compare C-
• strcmp compares the ASCII codes of the
  characters in the strings. Comparison is

slide 130
                   Comparing Strings
    strcmp(str1, str2): compares
    strings str1 and str2
            • returns 0 if the strings are the same, negative number if
              str1 < str2, and positive number if str1 > str2
              char myName[10] = "George";
              char yourName[10] = "Georgia";
              if (strcmp(myName,yourName) < 0)
                 cout << myName << " comes before "
                 << yourName << " in the alphabet";

slide 131
      4.15 The Conditional Operator
• Can use to create short if/else statements
• Format: expr ? expr : expr;

                  x<0 ? y=10 : z=20;

    First Expression:     2nd Expression:      3rd Expression:
    Expression to be      Executes if first    Executes if the first
    tested                expression is true   expression is false

slide 132
            The Conditional Operator
• The value of a conditional expression is
     – The value of the second expression if the first
       expression is true
     – The value of the third expression if the first
       expression is false
• Parentheses () may be needed in an
  expression due to precedence of conditional
slide 133
            4.16 The switch Statement
• Used to select among statements from
  several alternatives
• May be used instead of if/else if

slide 134
            switch statement format
switch (expression) //integer
  case exp1: statement1;
  case exp2: statement2;
  case expn: statementn;
  default:   statementn+1;
slide 135
   switch statement requirements
1) expression must be an integer variable or
   an expression that evaluates to an integer
2) exp1 through expn must be constant integer
   expressions or literals, and must be unique in
   the switch statement
3) default is optional but recommended

slide 136
            switch statement –
               how it works
1) expression is evaluated
2) The value of expression is compared
   against exp1 through expn.
3) If expression matches value expi, the
   program branches to the statement following
   expi and continues to the end of the switch
4) If no matching value is found, the program
   branches to the statement after default:
slide 137
            break statement
• Used to stop execution in the current block
• Also used to exit a switch statement
• Useful to execute a single case statement
  without executing the statements following it

slide 138
            Using switch with a menu
• switch statement is a natural choice for
  menu-driven program:
     – display menu
     – get user input
     – use user input as expression in switch
     – use menu choices as expr in case statements

slide 139
   4.17 Testing for File Open Errors
• Can test a file stream object to detect if an
  open operation failed:
        if (!infile)
          cout << "File open failure!";
• Can also use the fail member function
 slide 140
Chapter 5
5.1 The Increment and Decrement Operators
5.2 Introduction to Loops: The while Loop
5.3 Counters
5.4 Letting the User Control a Loop
5.5 Keeping a Running Total
5.6 Sentinels
5.7 Using a Loop to Read Data from a File
slide 142
5.8 The do-while and for Loops
5.9 Deciding Which Loop to Use
5.10 Nested Loops
5.11 Breaking Out of a Loop
5.12 The continue Statement
5.13 Using Loops for Data Validation

slide 143
5.1 The Increment and Decrement
• ++: add one to a variable
     val++; is the same as val = val + 1;
• --: subtract one from a variable
     val--; is the same as val = val – 1;
• can be used before (prefix) or after (postfix)
 a variable:
     ++val;      --val;

slide 144
            Prefix vs. Postfix
• ++ and -- operators can be used in
  complex statements and expressions
• prefix (++val, --val): increment or
  decrement, then return the value of the
• postfix (val++, val--): return the value of
  the variable, then increment or decrement

slide 145
            Prefix vs. Postfix - Examples
int num, val = 12;
cout << val++; // displays 12,
               // val is now 13;
cout << ++val; // sets val to 14,
               // then displays it
num = --val;   // sets val to 13,
               // stores 13 in num
num = val--;   // stores 13 in num,
               // sets val to 12
slide 146
    Notes on Increment, Decrement
• Can be used in expressions:
            result = num1++ + --num2;
• Must be applied to something that has a location in
  memory. Cannot have:
            result = (num1 + num2)++;
• Can be used in relational expressions:
            if (++num > limit)
            pre- and post-operations will cause different comparisons

slide 147
             5.2 Introduction to Loops:
                  The while Loop
• Loop: part of program that may execute > 1
  time (repeats)
• while loop:
            while (expression)
• statement; can also be a block of
  statements enclosed in { }

slide 148
            while Loop – How It Works
     while (expression)
• expression is evaluated
     – if true, then statement is executed, and
       expression is evaluated again
     – if false, then the the loop is finished and
       program statements following statement
slide 149
                while Loop Example
     int val = 5;
     while (val <= 8)
          cout << val++ < endl;
• produces output:

slide 150
            while Loop Notes
• no ; after (expression)
• while is a pretest loop – expression is
  evaluated before the loop executes
• loop must contain code to make
  expression become false
• Infinite loop: loop that does not stop

slide 151
              5.3 Counters
• Counter: variable that is incremented or
  decremented each time a loop repeats
• Can be used to control execution of the loop
  (loop control variable)
• Must be initialized before entering loop
• May be incremented/decremented either
  inside the loop or in the loop test

slide 152
       5.4 Letting the User Control a
• Program can be written so that user input
  determines loop repetition
• Used when program processes a list of items,
  and user knows the number of items
• User is prompted before loop. Their input is
  used to control number of repetitions

slide 153
  Letting the User Control a Loop -
int num = 1, limit;
cout << "Table of squares\n";
cout << "How high to go? ";
cin >> limit;
cout << "number square\n";
while (num <= limit)
{   cout << setw(5) << num << setw(6)
         << num*num << endl;
slide 154
              5.5 Keeping a Running Total
• running total: accumulated sum of numbers from each
  repetition of loop
• accumulator: variable that holds running total
   int sum=0, num=1; // sum is the
   while (num <= 10) // accumulator
   { sum += num;
   cout << "Sum of numbers 1 – 10 is"
        << sum << endl;
  slide 155
                5.6 Sentinels
• sentinel: value in a list of values that indicates
  end of data
• Special value that cannot be confused with a
  valid value, e.g., -999 for a test score
• Used to terminate input when user may not
  know how many values will be entered

slide 156
     5.7 Using a Loop to Read Data
               from a File
• eof() member function: returns true when
  the end of the file has been reached, false
• Can be tested in a while loop to continue
  execution until end of file:
            while (!infile.eof()) ...

slide 157
             5.8 The do-while
               and for Loops
• do-while: a posttest loop – execute the
  loop, then test the expression
• Format:
          statement; // or block in { }
        while (expression);
• Note ; after (expression)

slide 158
            do-while Loop Notes
• Loop always executes at least once
• Execution continues as long as expression
  is true, stops repetition when expression
  becomes false
• Useful in menu-driven programs to bring user
  back to menu to make another choice

slide 159
                      for Loop
• Useful for counter-controlled loop
• Format:
            for(initialization; test; update)
                statement; // or block in { }
• No ; after 3rd expression or after )

slide 160
              for Loop - Mechanics
for(initialization; test; update)
         statement; // or block in { }
1) Perform initialization
2) Evaluate test expression
  – If true, execute statement
  – If false, terminate loop execution
3) Execute update, then re-evaluate test
  slide 161
            for Loop - Example
int sum, num;

for (sum=0, num=1; num <= 10; num++)
  sum += num;

cout << "Sum of numbers 1 – 10 is"
     << sum << endl;

slide 162
              for Loop - Modifications
• Can omit initialization if already done:
       int sum = 0, num = 1;
       for (; num <= 10; num++)
           sum += num;
• Can declare variables in initialization:
    int sum = 0;
    for (int num=0; num <= 10; num++)
          sum += num;
    scope of variable num is the for loop
  slide 163
             for Loop - Modifications
• Can omit update if done in loop:
        for (sum = 0, num = 1; num <= 10;)
            sum += num++;

• Can omit test – may get infinite loop:
      for (sum = 0, num = 1; ; num++)
          sum += num;

 slide 164
            5.9 Deciding Which Loop
                     to Use
• while: pretest loop; loop body may not be
  executed at all
• do-while: posttest loop; loop body will
  always be executed at least once
• for: pretest loop with initialization and upate
  expression; useful with counters, or if precise
  number of repetitions is needed

slide 165
            5.10 Nested Loops
• A nested loop is a loop inside the body of
  another loop
• Inner (inside), outer (outside) loops:
   for (row=1; row<=3; row++) //outer
    for (col=1; col<=3; col++)//inner
       cout << row * col << endl;

slide 166
            Nested Loops - Notes
• Inner loop goes through all repetitions for
  each repetition of outer loop
• Inner loop repetitions complete sooner than
  outer loop
• Total number of repetitions for inner loop is
  product of number of repetitions of the two
  loops. In previous example, inner loop
  repeats 9 times

slide 167
            5.11 Breaking Out of a Loop
• Can use break to terminate execution of a
• Use sparingly if at all – makes code harder to
  understand and debug
• When used in an inner loop, terminates that
  loop only and goes back to outer loop

slide 168
    5.12 The continue Statement
• Can use continue to go to end of loop and
  prepare for next repetition
     – while, do-while loops: go to test, repeat loop
      if test passes
     – for loop: perform update step, then test, then
      repeat loop if test passes
• Use sparingly – like break, can make
  program logic hard to follow
slide 169
             5.13 Using Loops for Data
• Can design a loop to repeat execution until valid
  input is entered:
            cout << "Enter a test score "
                 << "in the range 0-100: ";
            cin >> score;
            while (score < 0 || score > 100)
            {     cout << "Score out of range - "
                       << "reenter: ";
                  cin >> score;
slide 170
Chapter 6
6.1 Modular Programming
6.2 Defining and Calling Functions
6.3 Function Prototypes
6.4 Sending Data into a Function
6.5 Passing Data by Value
6.6 Using Functions in a Menu-Driven Program
6.7 The return Statement
6.8 Returning a Value from a Function
slide 172
6.10 Local and Global Variables
6.11 Static Local Variables
6.12 Default Arguments
6.13 Using Reference Variables as Parameters
6.14 Overloading Functions
6.15 The exit() Function
6.16 Stubs and Drivers
6.9 Returning a Boolean Value
slide 173
            6.1 Modular Programming
• Modular programming: breaking a program
  up into smaller, manageable functions or
• Function: a collection of statements to
  perform a task
• Motivation for modular programming:
     – Improves maintainability of programs
     – Simplifies the process of writing programs

slide 174
6.2 Defining and Calling Functions

• Function call: statement causes a function to
• Function definition: statements that make up
  a function

slide 175
              Function Definition
• Definition includes:
     – return type: data type of the value that function
       returns to the part of the program that called it
     – name: name of the function. Function names
       follow same rules as variables
     – parameter list: variables containing values
       passed to the function
     – body: statements that perform the function’s task,
       enclosed in {}
slide 176
             Function Return Type
• If a function returns a value, the type of the
  value must be indicated:
        int main()
• If a function does not return a value, its return
  type is void:
        void printHeading()
             cout << "\tMonthly Sales\n";
 slide 177
                  Calling a Function
• To call a function, use the function name
  followed by () and ;
• When called, program executes the body of
  the called function
• After the function terminates, execution
  resumes in the calling function at point of call.

slide 178
               Calling Functions
• main can call any number of functions
• Functions can call other functions
• Compiler must know the following about a
  function before it is called:
     – name
     – return type
     – number of parameters
     – data type of each parameter
slide 179
            Function Documentation
    Function definition should be preceded by
    comments that indicate
     – Purpose of the function
     – How it works, what it does
     – Input values that it expects, if any
     – Output that it produces, if any
     – Values that it returns, if any

slide 180
              6.3 Function Prototypes
• Ways to notify the compiler about a function
  before a call to the function:
     – Place function definition before calling function’s
     – Use a function prototype (function declaration) –
       like the function definition without the body
            • Header: void printHeading()
            • Prototype: void printHeading();

slide 181
             Prototype Notes
• Place prototypes near top of program
• Program must include either prototype or full
  function definition before any call to the
  function – compiler error otherwise
• When using prototypes, can place function
  definitions in any order in source file

slide 182
                  6.4 Sending Data
                   into a Function
• Can pass values into a function at time of call:
            c = sqrt(a*a + b*b);
• Values passed to function are arguments
• Variables in function that hold values passed
  as arguments are parameters

slide 183
       Other Parameter Terminology
• A parameter can also be called a formal
  parameter or a formal argument
• An argument can also be called an actual
  parameter or an actual argument

slide 184
            Parameters, Prototypes,
            and Function Headings
• For each function argument,
   – the prototype must include the data type of each
     parameter in its ()
   – the header must include a declaration for each
     parameter in its ()
     void evenOrOdd(int); //prototype
     void evenOrOdd(int num) //header
     evenOrOdd(val);              //call
slide 185
               Function Call Notes
• Value of argument is copied into parameter when the
  function is called
• A parameter’s scope is the function which uses it
• Function can have > 1 parameter
• There must be a data type listed in the prototype () and
  an argument declaration in the function header () for
  each parameter
• Arguments will be promoted/demoted as necessary to
  match parameters

   slide 186
            Calling Functions with
             Multiple Arguments
    When calling a function with multiple
     – the number of arguments in the call must match
       the prototype and definition
     – the first argument will be used to initialize the first
       parameter, the second argument to initialize the
       second parameter, etc.

slide 187
            6.5 Passing Data by Value
• Pass by value: when an argument is passed
  to a function, its value is copied into the
• Changes to the parameter in the function do
  not affect the value of the argument

slide 188
             Passing Information to
             Parameters by Value
• Example: int val=5;
            val                           num
             5                             5
    argument in                        parameter in
   calling function                 evenOrOdd function

• evenOrOdd can change variable num, but it
  will have no effect on variable val
slide 189
               6.6 Using Functions in
               Menu-Driven Programs
• Functions can be used
     – to implement user choices from menu
     – to implement general-purpose tasks:
            • Higher-level functions can call general-purpose
              functions, minimizing the total number of functions
              and speeding program development time

slide 190
            6.7 The return Statement
• Used to end execution of a function
• Can be placed anywhere in a function
     – Statements that follow the return statement will
       not be executed
• Can be used to prevent abnormal termination
  of program
• Without a return statement, the function
  ends at its last }
slide 191
            6.8 Returning a Value
               From a Function
• return statement can be used to return a
  value from function to the point of call
• Prototype and definition must indicate data
  type of return value (not void)
• Calling function should use return value:
     – assign it to a variable
     – send it to cout
     – use it in an expression
slide 192
       6.9 Returning a Boolean Value
• Function can return true or false
• Declare return type in function prototype and
  heading as bool
• Function body must contain return
  statement(s) that return true or false
• Calling function can use return value in a
  relational expression

slide 193
             Boolean return Example
bool validTest(int);       // prototype
bool validTest(int test) // header
  int lScore = 0, hScore = 100;
  if (test >= lScore && test <= hScore)
     return true;
     return false;
if (validTest(score)) {...} // call
 slide 194
   6.10 Local and Global Variables
• local variable: defined within a function or
  block, accessible only within the function or
• Other functions and blocks can define
  variables with the same name
• When a function is called, local variables in
  the calling function are not accessible from
  within the called function

slide 195
            Local and Global Variables
• global variable: defined outside all functions,
  accessible to all functions within its scope
• Easy way to share large amounts of data
  between functions
• Scope of a global variable: program from point
  of definition to the end
• Use sparingly

slide 196
            Initializing Local and Global
• Local variables must be initialized by
• Global variables are initialized to 0 (numeric)
  or NULL (character) when variable is defined

slide 197
 Local and Global Variable Names
• Local variables can have same names as
  global variables
• When a function contains a local variable that
  has the same name as a global variable, the
  global variable is unavailable from within the
  function. The local definition “hides” the
  global definition

slide 198
            6.11 Static Local Variables
• Local variables only exist while function is
  executing. When function terminates,
  contents of local variables are lost
• static local variables retain their contents
  between function calls
• static local variables are defined and
  initialized only the first time the function is
  executed. 0 is default initialization

slide 199
             6.12 Default Arguments
  Default argument is passed automatically to a
  function if argument is missing on the function
• Must be a constant declared in prototype:
       void evenOrOdd(int = 0);
• Can be declared in header if no prototype
• Multi-parameter functions may have default
  arguments for some or all of them:
       int getSum(int, int=0, int=0);
 slide 200
              Default Arguments
• If not all parameters to a function have default
  values, the defaultless ones are declared first in
  the parameter list:
  int getSum(int, int=0, int=0);// OK
  int getSum(int, int=0, int); // NO
• When an argument is omitted from a function call,
  all arguments after it must also be omitted:
     sum = getSum(num1, num2);          // OK
     sum = getSum(num1, , num3);        // NO

  slide 201
    6.13 Using Reference Variables
            as Parameters
• Mechanism that allows a function to work with
  the original argument from the function call, not
  a copy of the argument
• Allows the function to modify values stored in
  the calling environment
• Provides a way for the function to ‘return’ > 1

slide 202
               Passing by Reference
• A reference variable is an alias for another
• Defined with an ampersand (&)
            void getDimensions(int&, int&);
• Changes to a reference variable are made to
  the variable it refers to
• Use reference variables to implement
  passing parameters by reference
slide 203
       Pass by Reference - Example
void sqareIt(int &); //prototype
void squareIt(int &num)
    num *= num;

int localVar = 5;
squareIt(localVar);   // now has 25
slide 204
             Reference Variable Notes
• Each reference parameter must contain &
• Space between type and & is unimportant
• Must use & in both prototype and header
• Argument passed to reference parameter must be a
  variable – cannot be an expression or constant
• Use when appropriate – don’t use when argument
  should not be changed by function, or if function needs
  to return only 1 value

 slide 205
            6.14 Overloading Functions
• Overloaded functions have the same name
  but different parameter lists
• Can be used to create functions that perform
  the same task but take different parameter
  types or different number of parameters
• Compiler will determine which version of
  function to call by argument and parameter
slide 206
    Function Overloading Examples
Using these overloaded functions,
void        getDimensions(int);         //    1
void        getDimensions(int, int);    //    2
void        getDimensions(int, float); //     3
void        getDimensions(float, float);//    4
the compiler will use them as follows:
int length, width;
float base, height;
getDimensions(length);                   //   1
getDimensions(length, width);            //   2
getDimensions(length, height);           //   3
getDimensions(height, base);             //   4
slide 207
            6.15 The exit() Function
• Terminates execution of a program
• Can be called from any function
• Can pass an int value to operating system
  to indicate status of program termination
• Usually used for abnormal termination of
• Requires cstdlib header file
slide 208
             6.16 Stubs and Drivers
• Stub: dummy function in place of actual
• Usually displays a message indicating it was
  called. May also display parameters
• Driver: function that tests a function by calling
• Useful for testing and debugging program and
  function logic and design
 slide 209
Chapter 7
7.1         Arrays Hold Multiple Values
7.2         Accessing Array Elements
7.3         No Bounds Checking in C++
7.4         Array Initialization
7.5         Processing Array Contents
7.6         Using Parallel Arrays

slide 211
7.7 Arrays as Function Arguments
7.8 Two-Dimensional Arrays
7.9 Arrays of Strings
7.10 Arrays with Three or More Dimensions
7.13 Introduction to the STL vector

slide 212
   7.1 Arrays Hold Multiple Values
• Array: variable that can store multiple values
  of the same type
• Values are stored in adjacent memory
• Declared using [] operator:
            int tests[5];

slide 213
               Array - Memory Layout
• The definition:
            int tests[5];
    allocates the following memory:

            first     second    third     fourth    fifth
            element   element   element   element   element

slide 214
             Array Terminology
In the definition int tests[5];
• int is the data type of the array elements
• tests is the name of the array
• 5, in [5], is the size declarator. It shows the
  number of elements in the array.
• The size of an array is (number of elements) *
  (size of each element)
 slide 215
              Array Terminology
• The size of an array is:
  – the total number of bytes allocated for it
  – (number of elements) * (number of bytes for each
• Examples:
     int tests[5] is an array of 20 bytes, assuming 4
     bytes for an int
     long double measures[10]is an array of 80 bytes,
     assuming 8 bytes for a long double
  slide 216
     7.2 Accessing Array Elements
• Each array element has a subscript, used to
  access the element.
• Subscripts start at 0
             0          1   2   3   4

slide 217
             Accessing Array Elements
• Array elements can be used as regular variables:
            tests[0] = 79;
            cout << tests[0];
            cin >> tests[1];
            tests[4] = tests[0] + tests[1];
• Arrays must be accessed via individual elements:
            cout << tests; // not legal

slide 218
            Accessing Array Contents
• Can access element with constant subscript:
       cout << tests[3] << endl;
• Can use integer expression as subscript:
       for (i = 0; i < 5;i++)
          cout << tests[i] << endl;

slide 219
            Global vs. Local Array
• Global array  all elements initialized to 0
• Local array  all elements uninitialized by

slide 220
             7.3 No Bounds Checking
                     in C++
• C++ does not check if an array subscript is in
  the range of values for subscripts of the array
• Can access memory using subscripts that is
  before or after the memory for an array
• Can corrupt other memory locations, crash
  program, or lock up computer
• Not recommended

 slide 221
             7.4 Array Initialization
• Can be initialized during program execution
  with assignment statements:
       tests[0] = 79;
       tests[1] = 82; // etc.
• Can be initialized at array definition with an
  initialization list:
       int tests[5] = {79,82,91,77,84};
• Initialization list cannot exceed array size
 slide 222
             Partial Array Initialization
• If array is initialized at definition with fewer
  initial values than the size declarator of the
  array, the remaining elements will be set to 0:
        int tests[5] = {79, 82};

• Initial values used in order; cannot skip over
           79     82      0       0       0
  elements to initialize noncontiguous range

 slide 223
                 Implicit Array Sizing
• Can determine array size by the size of the
  initialization list:
            short quizzes[]={12,17,15,11};
               12      17      15       11

• Must use either array size declarator or
  initialization list at array definition

slide 224
             Initializing With a String
• Character array can be initialized by enclosing
  string in " ":
       char fName[6] = "Henry";
• Must leave room for \0 at end of array
• If initializing character-by-character, must add
  in \0 explicitly:
    char fName[6] =
   { 'H', 'e', 'n', 'r', 'y', '\0'};

 slide 225
     7.5 Processing Array Contents
• Array elements can be treated as ordinary
  variables of the same type as the array
• When using ++, -- operators, don’t confuse
  the element with the subscript:
            tests[i]++; // add 1 to tests[i]
            tests[i++]; // increment i, no
                        // effect on tests

slide 226
               Array Assignment
To copy one array to another,
• don’t try to assign one array to the other:
        newTests = tests;
• assign element-by-element:
        for (i=0; i<5; i++)
           newTests[i] = tests[i];

 slide 227
            Display the Contents of
                   an Array
• Can display character array by using its name:
       cout << fName << endl;
• For other types of arrays, must go element-by-
       for (i=0; i<5; i++)
          cout << tests[i] << endl;

slide 228
               Sum of Array Elements
• Use a simple loop to add together array
            int tnum;
            float average, sum = 0;
            for(tnum = 0; tnum < 5; tnum++)
                 sum += tests[tnum];
• Once summed, can compute average:
            average = sum/5;

slide 229
            7.6 Using Parallel Arrays
• Parallel arrays: two or more arrays that
  contain related data
• Subscript is used to relate arrays: elements
  at same subscript are related
• Arrays may be of different types

slide 230
            Parallel Array Example
    string name[5]; // student name
    float average[5];// course average
    char grade[5];    // course grade
    for(int i = 0; i < 5; i++)
        cout << "Student: " << name[i]
             << " average: " << average[i]
             << " grade: " << grade[i]
             << endl;
slide 231
             7.7 Arrays as Function
• To pass an array to a function, just use the array
• To define a function that takes an array
  parameter, use empty [] for array argument:
       void showScores(int []);
                // function prototype
       void showScores(int tests[])
                // function header

 slide 232
         Arrays as Function Arguments
• When passing an array to a function, it is common to pass
  array size so that function knows how many elements to
     showScores(tests, 5);
• Array size must also be reflected in prototype, header:
  void showScores(int [], int);
               // function prototype
  void showScores(int tests[], int size)
               // function header

   slide 233
       Modifying Arrays in Functions
• Array names in functions are similar to
  reference variables – changes made to array
  in a function are reflected in actual array in
  calling function
• Need to exercise caution that array is not
  inadvertantly changed by a function

slide 234
        7.8 Two-Dimensional Arrays
• Can define one array for multiple sets of data
• Like a table in a spreadsheet
• Use two size declarators in definition:
            int exams[4][3];
• First declarator is number of rows; second is
  number of columns

slide 235
                Two-Dimensional Array
     int exams[4][3];
                exams[0][0]   exams[0][1]   exams[0][2]
            o   exams[1][0]   exams[1][1]   exams[1][2]
            w   exams[2][0]   exams[2][1]   exams[2][2]
                exams[3][0]   exams[3][1]   exams[3][2]

• Use two subscripts to access element:
     exams[2][2] = 86;
slide 236
              Initialization at Definition
• Two-dimensional arrays are initialized row-
            int exams[2][2] = { {84, 78},
                  84 78         {92, 97} };
                  92   97

• Can omit inner { }, some initial values in a
  row – array elements without initial values
  will be set to 0 or NULL

slide 237
            Two-Dimensional Array as
              Parameter, Argument
• Use array name as argument in function call:
       getExams(exams, 2);
• Use empty [] for row, size declarator for
  column in prototype, header:
      void getExams(int [][2], int);
                        // prototype
      void getExams(int exams[][2], int rows)
                        // header

slide 238
                 7.9 Array of Strings
• Use a two-dimensional array of characters as
  an array of strings:
            char students[3][10] =
            { "Ann", "Bill", "Cindy" };
• Each row contains one string
• Can use row subscript to reference the string:
            cout << students[i];

slide 239
      7.10 Arrays with Three or More
• Can define arrays with any number of
      short rectSolid(2,3,5);
      float timeGrid(3,4,3,4);
• When used as parameter, specify all but 1st
  dimension in prototype, heading:
      void getRectSolid(short [][3][5]);

 slide 240
            7.13 Introduction to the STL
• Defined in the Standard Template Library
  (Chapter 16)
• Can hold values of any type:
            vector<int> scores;
• Automatically adds space as more is
  needed – no need to determine size at
• Can use [] to access elements
slide 241
                Declaring Vectors
• Vectors require vector header file
• Declare a vector:
       vector<int> scores;
• Declare a vector with initial size 30:
       vector<int> scores(30);
• Declare a vector and initialize all elements to 0:
       vector<int> scores(30, 0);
• Declare a vector initialized to size and contents of
  another vector:
       vector<int> finals(scores);
  slide 242
              Growing a Vector’s Size
• Use size member function to determine size
  of a vector:
            howbig = scores.size();
• Use push_back member function to add
  element to a full array or to an array that had
  no defined size:

slide 243
            Removing Vector Elements
• Use pop_back member function to remove last
  element from vector:
• To remove all contents of vector, use clear
  member function:
• To determine if vector is empty, use empty member
            while (!scores.empty()) ...

slide 244
       Other Useful Member Functions
Member         Description                            Example
at(elt)        Returns the value of the element at    cout <<
               position elt in the vector              vec1.at(i);
capacity()     Returns the maximum number of          maxelts =
               elements a vector can store without     vec1.capacity();
               allocating more memory
reverse()      Reverse the order of the elements in   vec1.reverse();
               a vector
resize         Add elements to a vector, optionally   vec1.resize(5,0);
(elts,val)     initializes them
swap(vec2)     Exchange the contents of two           vec1.swap(vec2);
   slide 245
         Chapter 8
Searching and Sorting Arrays
8.1 Introduction to Search Algorithms
8.3 Introduction to Sorting Algorithms
8.5 Sorting and Searching Vectors

slide 247
            8.1 Introduction to Search
• Search: locate an item in a list of information
• Two algorithms (methods):
     – Linear search
     – Binary search

slide 248
                          Linear Search
• Algorithm:
            set found to false; set position to –1; set index to 0
            while index < number of elts. and found is false
               if list[index] is equal to search value
                  found = true
                  position = index
               end if
               add 1 to index
            end while
            return position
slide 249
            Linear Search - Example
• Array numlist contains:
            17   23   5   11   2   29   3

• Searching for the the value 11, linear search
  examines 17, 23, 5, and 11
• Searching for the the value 7, linear search
  examines 17, 23, 5, 11, 2, 29, and 3
slide 250
            Linear Search - Tradeoffs
• Benefits:
     – Easy algorithm to understand
     – Array can be in any order
• Disadvantages:
     – Inefficient (slow): for array of N elements,
       examines N/2 elements on average for value in
       array, N elements for value not in array

slide 251
                       Binary Search
   Requires array elements to be in order
1. Divides the array into three sections:
  –      middle element
  –      elements on one side of the middle element
  –      elements on the other side of the middle element
2. If the middle element is the correct value, done.
   Otherwise, go to step 1. using only the half of the array
   that may contain the correct value.
3. Continue steps 1. and 2. until either the value is found
   or there are no more elements to examine

  slide 252
            Binary Search - Example
• Array numlist2 contains:
            2   3   5   11   17   23   29

• Searching for the the value 11, binary search
  examines 11 and stops
• Searching for the the value 7, linear search
  examines 11, 3, 5, and stops
slide 253
            Binary Search - Tradeoffs
• Benefits:
     – Much more efficient than linear search. For array
       of N elements, performs at most log2N
• Disadvantages:
     – Requires that array elements be sorted

slide 254
            8.3 Introduction to Sorting
• Sort: arrange values into an order:
     – Alphabetical
     – Ascending numeric
     – Descending numeric
• Two algorithms considered here:
     – Bubble sort
     – Selection sort

slide 255
                         Bubble Sort
   – Compare 1st two elements
         • If out of order, exchange them to put in order
   – Move down one element, compare 2nd and 3rd
     elements, exchange if necessary. Continue until
     end of array.
   – Pass through array again, exchanging as necessary
   – Repeat until pass made with no exchanges
 slide 256
                 Bubble Sort - Example
 Array numlist3 contains:
               17     23        5       11

compare values
17 and 23 – in correct                          compare values 23 and
order, so no exchange                           11 – not in correct order,
                                                so exchange them
                    compare values 23 and
                    5 – not in correct order,
                    so exchange them

   slide 257
                Bubble Sort – Example (2)
 After first pass, array numlist3 contains:
                17      5        11       23

compare values 17 and
5 – not in correct order,                          compare values 17 and
so exchange them                                   23 – in correct order,
                                                   so no exchange
                      compare values 17 and
                      11 – not in correct order,
                      so exchange them

    slide 258
               Bubble Sort – Example (3)
 After second pass, array numlist3 contains:
               5     11       17      23

compare values 5 and
11 – in correct order,                         compare values 17 and
so no exchange                                 23 – in correct order,
                                               so no exchange
                     compare values 11 and
                     17 – in correct order,
                     so no exchange           No exchanges, so
                                              array is in order
   slide 259
            Bubble Sort - Tradeoffs
• Benefit:
     – Easy to understand and implement
• Disadvantage:
     – Inefficient: slow for large arrays

slide 260
                  Selection Sort
• Concept for sort in ascending order:
     – Locate smallest element in array. Exchange it
       with element in position 0
     – Locate next smallest element in array. Exchange
       it with element in position 1.
     – Continue until all elements are arranged in order

slide 261
            Selection Sort - Example
       Array numlist contains:
             11   2    29   3

1. Smallest element is 2. Exchange 2 with
   element in 1st position in array:
             2    11   29   3

slide 262
            Selection Sort – Example (2)
2. Next smallest element is 3. Exchange 3 with
   element in 2nd position in array:
               2   3   29   11
3. Next smallest element is 11. Exchange 11
   with element in 3rd position in array:
               2   3   11   29

slide 263
            Selection Sort - Tradeoffs
• Benefit:
     – More efficient than Bubble Sort, since fewer
• Disadvantage:
     – May not be as easy as Bubble Sort to understand

slide 264
            8.5 Sorting and Searching
• Sorting and searching algorithms can be
  applied to vectors as well as arrays
• Need slight modifications to functions to use
  vector arguments:
     – vector <type> & used in prototype
     – No need to indicate vector size – functions can
       use size member function to calculate

slide 265
Chapter 9
9.1 Getting the Address of a Variable
9.2 Pointer Variables
9.3 The Relationship Between Arrays and
9.4 Pointer Arithmetic
9.5 Initializing Pointers

slide 267
9.6         Comparing Pointers
9.7         Pointers as Function Parameters
9.8         Dynamic Memory Allocation
9.9         Returning Pointers from Functions

slide 268
            9.1 Getting the Address of a
• Each variable in program is stored at a
  unique address
• Use address operator & to get address of a
            int num = -23;
            cout << &num; // prints address
                          // in hexadecimal

slide 269
            9.2 Pointer Variables
• Pointer variable (pointer): variable that holds
  an address
• Can perform some tasks more easily with an
  address than by accessing memory via a
  symbolic name:
     – Accessing unnamed memory locations
     – Array manipulation
     – etc.

slide 270
                   Pointer Variables
• Definition:
            int   *intptr;
• Read as:
  “intptr can hold the address of an int”
• Spacing in definition does not matter:
            int * intptr;    // same as above
            int* intptr;     // same as above

slide 271
                   Pointer Variables
• Assignment:
     int *intptr;
     intptr = &num;
• Memory layout:
                         num        intptr
                         25         0x4a00
      address of num: 0x4a00
• Can access num using intptr and indirection
  operator *:
            cout << *intptr << endl; // prints 25

slide 272
       9.3 The Relationship Between
            Arrays and Pointers
  • Array name is starting address of array
              int vals[] = {4, 7, 11};
                              4    7   11
starting address of vals: 0x4a00

              cout << vals;             // displays
                                        // 0x4a00
              cout << vals[0];          // displays 4
  slide 273
 The Relationship Between Arrays
           and Pointers
• Array name can be used as a pointer
            int vals[] = {4, 7, 11};
            cout << *vals;    // displays 4
• Pointer can be used as an array name:
            int *valptr = vals;
            cout << valptr[1]; // displays 7

slide 274
             Pointers in Expressions
   int vals[]={4,7,11}, *valptr;
   valptr = vals;
What is valptr + 1? It means (address in
 valptr) + (1 * size of an int)
   cout << *(valptr+1); //displays 7
   cout << *(valptr+2); //displays 11
Must use ( ) in expression
 slide 275
                            Array Access
• Array elements can be accessed in many ways:
          Array access method            Example

     array name and []          vals[2] = 17;

     pointer to array and []    valptr[2] = 17;

     array name and subscript   *(vals + 2) = 17;
     pointer to array and       *(valptr + 2) = 17;
     subscript arithmetic

  slide 276
             Array Access
• Conversion: vals[i] is equivalent to
  *(vals + i)
• No bounds checking performed on array
  access, whether using array name or a

slide 277
                 9.4 Pointer Arithmetic
   • Operations on pointer variables:
Operation                  Example
                           int vals[]={4,7,11};
                           int *valptr = vals;
++, --                     valptr++; // points at 7
                           valptr--; // now points at 4
+, - (pointer and int)     cout << *(valptr + 2); // 11

+=, -= (pointer            valptr = vals; // points at 4
and int)                   valptr += 2;   // points at 11
- (pointer from pointer)   cout << valptr–val; // difference
                           //(number of ints) between valptr
                           // and val
   slide 278
             9.5 Initializing Pointers
• Can initialize at definition time:
       int num, *numptr = &num;
       int val[3], *valptr = val;
• Cannot mix data types:
       float cost;
       int *ptr = &cost; // won’t work
• Can test for an invalid address for ptr with:
       if (!ptr) ...
 slide 279
              9.6 Comparing Pointers
• Relational operators (<, >=, etc.) can be used
  to compare addresses in pointers
• Comparing addresses in pointers is not the
  same as comparing contents pointed at by
            if (ptr1 == ptr2)   //   compares
                                //   addresses
            if (*ptr1 == *ptr2) //   compares
                                //   contents
slide 280
                9.7 Pointers as Function
•     A pointer can be parameter
•     Works like reference variable to allow change to argument from
      within function
•     Requires:
     1) asterisk * on parameter in prototype and heading
     void getNum(int *ptr); // ptr is pointer to an int
     2) asterisk * in body to dereference the pointer
      cin >> *ptr;
     3) address as argument to the function
     getNum(&num);        // pass address of num to getNum

    slide 281
   Pointers as Function Parameters
void swap(int *x, int *y)
{   int temp;
    temp = *x;
    *x = *y;
    *y = temp;

int num1 = 2, num2 = -3;
swap(&num1, &num2);
 slide 282
   9.8 Dynamic Memory Allocation
• Can allocate storage for a variable while
  program is running
• Computer returns address of newly allocated
• Uses new operator to allocate memory:
            float *fptr;
            fptr = new float;
• new returns address of memory location
slide 283
            Dynamic Memory Allocation
• Can also use new to allocate array:
            arrayPtr = new float[25];
• Can then use [] or pointer arithmetic to access
            for(i = 0; i < 25; i++)
               *arrayptr[i] = i * i;
            for(i = 0; i < 25; i++)
               *(arrayptr + i) = i * i;
• Program will terminate if not enough memory
  available to allocate
slide 284
            Releasing Dynamic Memory
• Use delete to free dynamic memory:
            delete fptr;
• Use [] to free dynamic array:
            delete [] arrayptr;
• Only use delete with dynamic memory!

slide 285
            9.9 Returning Pointers from
• Pointer can be return type of function:
            int* newNum();
• Function must not return a pointer to a local
  variable in the function
• Function should only return a pointer:
     – to data that was passed to the function as an
     – to dynamically allocated memory

slide 286
            Chapter 10
Characters, Strings, and the string
10.1   Character Testing
10.2   Character Case Conversion
10.3   Review of the Internal Storage of C-Strings
10.4   Library Functions for Working with C-Strings
10.5   String/Numeric Conversion Functions
10.6   Writing Your Own C-String Handling Functions
10.8   The C++ string Class

 slide 288
            10.1 Character Testing
  • require cctype header file
isalpha      true if arg. is a letter, false otherwise
isalnum      true if arg. is a letter or digit, false otherwise
isdigit      true if arg. is a digit 0-9, false otherwise
islower      true if arg. is lowercase letter, false otherwise
isprint      true if arg. is a printable character, false otherwise
ispunct      true if arg. is a punctuation character, false otherwise
isupper      true if arg. is an uppercase letter, false otherwise
isspace      true if arg. is a whitespace character, false otherwise
slide 289
  10.2 Character Case Conversion
• require cctype header file
• functions:
       toupper: if char argument is lowercase letter, return
       uppercase equivalent; otherwise, return input unchanged
       char greeting[] = "Hello!";
       cout << toupper[0]; // displays 'H'
       cout << toupper[1]; // displays 'E'
       cout << toupper[5]; // displays '!'

 slide 290
             Character Case Conversion
• functions:
       tolower: if char argument is uppercase letter,
       return lowercase equivalent; otherwise, return input
       char greeting[] = "Hello!";
       cout << tolower[0]; // displays 'h'
       cout << tolower[1]; // displays 'e'
       cout << tolower[5]; // displays '!'
 slide 291
              10.3 Review of the Internal
                 Storage of C-Strings
• C-string: sequence of characters stored in
  adjacent memory locations and terminated by
  NULL character
• String literal (string constant): sequence of
  characters enclosed in double quotes " " :
      "Hi there!"
              H   i   t   h   e   r   e   !   \0

  slide 292
                Review of the Internal
                Storage of C-Strings
• Array of chars can be used to define storage for
            char city[20];
• Leave room for NULL at end
• Can enter a value using cin or >>
     – Input is whitespace-terminated
     – No check to see if enough space
• For input containing whitespace, and to control
  amount of input, use cin.getline()

slide 293
            10.4 Library Functions for
             Working with C-Strings
• require cstring header file
• functions take one or more C-strings as
  arguments. Can use:
     – C-string name
     – pointer to C-string
     – literal string

slide 294
                 Library Functions for
                Working with C-Strings
  – strlen(str): returns length of C-string str
             char city[20] = "Missoula";
             cout << strlen(city); // prints 8
  – strcat(str1, str2): appends str2 to the end
    of str1
             char location[20] = "Missoula, ";
             char state[3] = "MT";
             strcat(location, state);
             // location now has "Missoula, MT"
 slide 295
               Library Functions for
              Working with C-Strings
  – strcpy(str1, str2): copies str2 to str1
         char fname[20] = "Maureen", name[20];
         strcpy(name, fname);
  Note: strcat and strcpy perform no bounds
   checking to determine if there is enough space in
   receiving character array to hold the string it is being

  slide 296
            C-string Inside a C-string
     – strstr(str1, str2): finds the first
       occurrence of str2 in str1. Returns a pointer to
       match, or NULL if no match.
            char river[10] = "Wabash";
            char word[5] = "aba";
            cout << strstr(state, word);
            // displays "abash"

slide 297
   10.5 String/Numeric Conversion
• require cstdlib header file
  atoi       C-string        converts C-string to an int value, returns
                             the value
  atol       C-string        converts C-string to a long value, returns
                             the value
  atof       C-string        converts C-string to a double value,
                             returns the value
  itoa       int,C-string,   converts 1st int parameter to a C-string,
             int             stores it in 2nd parameter. 3rd parameter is
                             base of converted value
slide 298
            String/Numeric Conversion
int iNum;
long lNum;
float fNum;
char intChar[10];
iNum = atoi("1234"); // puts 1234 in iNum
lNum = atol("5678"); // puts 5678 in lNum
fNum = atof("35.7"); // puts 35.7 in fNum
itoa(iNum, intChar, 8); // puts the string
   // "2322" (base 8 for 123410) in intChar
slide 299
            String/Numeric Conversion
                 Functions - Notes
• if C-string contains non-digits, results are
     – function may return result up to non-digit
     – function may return 0
• itoa does no bounds checking – make sure
  there is enough space to store the result

slide 300
   10.6 Writing Your Own C-String
        Handling Functions
• Designing C-String Handling Functions
     – can pass arrays or pointers to char arrays
     – Can perform bounds checking to ensure enough
       space for results
     – Can anticipate unexpected user input

slide 301
           10.8 The C++ string Class
• Special datatype supports working with strings
• #include <string>
• Can define string variables in programs:
  string firstName, lastName;
• Can receive values with assignment operator:
  firstName = "George";
  lastName = "Washington";
• Can be displayed via cout
  cout << firstName << " " << lastName;

   slide 302
            Input into a string Object
• Use getline function to put a line of input,
  possibly including spaces, into a string:
            string address;
            cout << "Enter your address: ";

slide 303
              string Comparison
• Can use relational operators directly to compare string
       string str1 = "George",
               str2 = "Georgia";
       if (str1 < str2)
         cout << str1 << " is less than "
               << str2;
• Comparison is performed similar to strcmp function.
  Result is true or false
  slide 304
    Other Definitions of C++ strings

Definition                 Meaning
string name;               defines an empty string object
string myname("Chris");    defines a string and initializes it
string yourname(myname);   defines a string and initializes it
string aname(myname, 3);   defines a string and initializes it with first 3
                           characters of myname
string verb(myname,3,2);   defines a string and initializes it with 2
                           characters from myname starting at position 3

string noname('A', 5);     defines string and initializes it to 5 'A's
   slide 305
             string Operators
>>           extracts characters from stream up to whitespace, insert
             into string
<<           inserts string into stream
=            assigns string on right to string object on left
+=           appends string on right to end of contents on left
+            concatenates two strings
[]           references character in string using array notation
>, >=, <,    relational operators for string comparison. Return true or
<=, ==, !=   false
slide 306
             string Operators
string word1, phrase;
string word2 = " Dog";
cin >> word1; // user enters "Hot Tamale"
              // word1 has "Hot"
phrase = word1 + word2; // phrase has
                        // "Hot Dog"
phrase += " on a bun";
for (int i = 0; i < 16; i++)
     cout << phrase[i]; // displays
               // "Hot Dog on a bun"
 slide 307
             string Member Functions
• Are behind many overloaded operators
• Categories:
   – assignment: assign, copy, data
   – modification: append, clear, erase, insert,
     replace, swap
   – space management: capacity, empty,
     length, resize, size
   – substrings: find, substr
   – comparison: compare

 slide 308
              string Member Functions
string word1, word2, phrase;
cin >> word1;          // word1 has "Hot"
word2.assign(" Dog");
phrase.append(word2); // phrase has "Hot Dog"
phrase.append(" with mustard relish", 13);
         // phrase has "Hot Dog with mustard"
phrase.insert(8, "on a bun ");
cout << phrase << endl; // displays
         // "Hot Dog on a bun with mustard"

  slide 309
  Chapter 11
Structured Data
11.1 Abstract Data Types
11.2 Combining Data into Structures
11.3 Accessing Structure Members
11.4 Initializing a Structure
11.5 Arrays of Structures
11.6 Nested Structures
 slide 311
11.7        Structures as Function Arguments
11.8        Returning a Structure from a Function
11.9        Pointers to Structures
11.10 When to Use ., When to Use ->, and
  When to Use *
11.11 Unions
slide 312
             11.1 Abstract Data Types
• A data type that specifies
  – values that can be stored (range or domain)
  – operations that can be done on the values
• User of an abstract data type does not need to
  know the implementation of the data type, e.g.,
  how the data is stored
• ADTs are created by programmers

 slide 313
            Abstraction and Data Types
• Abstraction: a definition that captures general
  characteristics without details
     – Ex: An abstract triangle is a 3-sided polygon. A
       specific triangle may be scalene, isosceles, or
• Data Type defines the values that can be
  stored in a variable and the operations that
  can be performed on it
slide 314
            11.2 Combining Data into
• Structure: C++ construct that allows multiple
  variables to be grouped together
• Format:
     struct <struct name>
       type1 field1;
       type2 field2;
       . . .
slide 315
       Example struct Declaration
     struct Student
     {                          structure tag

        int studentID;        structure members
        string name;
        short yearInSchool;
        float gpa;

slide 316
             struct Declaration Notes
• Must have ; after closing }
• struct names commonly begin with
  uppercase letter
• Multiple fields of same type can be in
  comma-separated list:
            string name,

slide 317
                 Defining Variables
• struct declaration does not allocate
  memory or create variables
• To define variables, use structure tag as type
  name:                     stu1
            Student stu1;


slide 318
             11.3 Accessing Structure
• Use the dot (.) operator to refer to members
  of struct variables:
            cin >> stu1.studentID;
            getline(cin, stu1.name);
            stu1.gpa = 3.75;
• Member variables can be used in any
  manner appropriate for their data type

slide 319
       Displaying a struct Variable
• To display the contents of a struct variable,
  must display each field separately, using the
  dot operator:
            cout   <<   stu1; // won’t work
            cout   <<   stu1.studentID << endl;
            cout   <<   stu1.name << endl;
            cout   <<   stu1.yearInSchool;
            cout   <<   " " << stu1.gpa;

slide 320
       Comparing struct Variables
• Cannot compare struct variables directly:
            if (stu1 == stu2) // won’t work

• Instead, must compare on a field basis:
     if (stu1.studentID ==
                stu2.studentID) ...

slide 321
             11.4 Initializing a Structure
• struct variable can be initialized when
   Student stu2 = (11465, "Joan", 2, 3.75);

• Can also be initialized member-by-member
  after definition:
       stu2.name = "Joan";
       stu2.gpa = 3.75;

 slide 322
      More on Initializing a Structure
• May initialize only some members:
            Student stu3 = (14579);
• Cannot skip over members:
            Student stu4 = (1234, "John", ,
                          2.83); // illegal
• Cannot initialize in the structure declaration,
  since this does not allocate memory

slide 323
            11.5 Arrays of Structures
• Structures can be defined in arrays
• Can be used in place of parallel arrays
     Student stuList[20];
• Individual structures accessible using
  subscript notation
• Fields within structures accessible using dot
     cout << stuList[5].studentID;
slide 324
               11.6 Nested Structures
    A structure can contain another structure as a
            struct PersonInfo
            {     string name,
            struct Student
            {     int studentID;
                  PersonInfo pData;
                  short yearInSchool;
                  float gpa;
slide 325
      Members of Nested Structures
• Use the dot operator multiple times to refer to
  fields of nested structures:

            Student stu5;
            stu5.pData.name = "Joanne";
            stu5.pData.city = "Tulsa";

slide 326
            11.7 Structures as Function
• May pass members of struct variables to
• May pass entire struct variables to functions:
• Can use reference parameter if function needs
  to modify contents of structure variable

slide 327
 Structures as Function Arguments
              - Notes
• Using value parameter for structure can slow
  down a program, waste space
• Using a reference parameter will speed up
  program, but function may change data in
• Using a const reference parameter allows
  read-only access to reference parameter, does
  not waste space, speed

slide 328
 11.8 Returning a Structure from a
• Function can return a struct:
   Student getStuData();        // prototype
   stu1 = getStuData();         // call
• Function must define a local structure
   – for internal use
   – for use with return statement

 slide 329
            Returning a Structure from a
                Function - Example
Student getStuData()
{   Student tmpStu;
    cin >> tmpStu.studentID;
    getline(cin, tmpStu.pData.name);
    getline(cin, tmpStu.pData.address);
   getline(cin, tmpStu.pData.city);
   cin >> tmpStu.yearInSchool;
   cin >> tmpStu.gpa;
   return tmpStu;
slide 330
            11.9 Pointers to Structures
• A structure variable has an address
• Pointers to structures are variables that can
  hold the address of a structure:
     Student *stuPtr;
• Can use & operator to assign address:
     stuPtr = & stu1;
• Structure pointer can be a function parameter
slide 331
 Accessing Structure Members via
        Pointer Variables
• Must use () to dereference pointer variable,
  not field within structure:
     cout << (*stuPtr).studentID;
• Can use structure pointer operator to
  eliminate () and use clearer notation:
     cout << stuPtr->studentID;

slide 332
    11.10 When to Use ., When to
     Use ->, and When to Use *
• Consider the following:
   struct Xmpl
      int *intPtr;
   Xmpl xmpl1, *xmplPtr = &xmpl1;
• *xmpl1.intPtr accesses the value pointed at by
• *xmplPtr->intPtr does the same thing
slide 333
                 11.11 Unions
• Similar to a struct, but
     – all members share a single memory location, and
     – only 1 member of the union can be used at a
• Declared using union, otherwise the same
  as struct
• Variables defined as for struct variables

slide 334
                 Anonymous Union
• A union without a union tag:
            union { ... };
• Must use static if declared outside of a
• Allocates memory at declaration time
• Can refer to members directly without dot
• Uses only 1 memory location, saves space
slide 335
      Chapter 12
Advanced File Operations
12.1 File Operations
12.2 File Output Formatting
12.3 Passing File Stream Objects to Functions
12.4 More Detailed Error Testing
12.5 Member Functions for Reading and
  Writing Files

slide 337
12.6 Working with Multiple Files
12.7 Binary Files
12.8 Creating Records with Structures
12.9 Random Access Files
12.10 Opening a File for Both Input and Output

slide 338
            12.1 File Operations
• File: a set of data stored on a computer, often
  on a disk drive
• Programs can read from, write to files
• Used in many applications:
     – Word processing
     – Databases
     – Spreadsheets
     – Compilers
slide 339
                       Using Files
1. Requires fstream header file
     -      use ifstream data type for input files
     -      use ofstream data type for output files
     -      use fstream data type for both input, output
2. Can use >>, << to read from, write to a file
3. Can use eof member function to test for
   end of input file
slide 340
                  fstream Object
• fstream object can be used for either input or output
• Must specify mode on the open statement
• Sample modes:
       ios::in – input
       ios::out – output
• Can be combined on open call:
       dFile.open("class.txt", ios::in | ios::out);

 slide 341
            Using Files - Example
 // copy 10 numbers between files
                      // open the files
 fstream infile("input.txt", ios::in);
 fstream outfile("output.txt", ios::out);
 int num;
 for (int i = 1; i <= 10; i++)
    infile >> num;    // use the files
    outfile << num;
 infile.close();      // close the files
slide 342
               Default File Open Modes
• ifstream:
     – open for input only
     – file cannot be written to
     – open fails if file does not exist
• ofstream:
     –      open for output only
     –      file cannot be read from
     –      file created if no file exists
     –      file contents erased if file exists

slide 343
               More File Open Details
• Can use filename, flags in definition:
            ifstream gradeList("grades.txt");
• File stream object set to 0 (false) if open
            if (!gradeList) ...
• Can also check fail member function to
  detect file open error:
            if (gradeList.fail()) ...

slide 344
                 File Mode Flags
ios::app         create new file, or append to end of existing file
ios::ate         go to end of existing file; write anywhere
ios::binary      read/write in binary mode (not text mode)
ios::in          open for input
ios::nocreate    open fails if file does not exist
ios::noreplace   open fails if file does exist
ios::out         open for output
ios::trunc       delete contents of file upon open

 slide 345
            File Naming Conventions
• Different systems may have requirements on how to
  name a file:
     – MS-DOS: up to 8 characters, a dot, up to a 3 character
       extension. No spaces. Example:
• Extension often indicates purpose of file:
     – .doc: Microsoft Word file
     – .cpp: C++ source file
     – .h: C++ header file
slide 346
            12.2 File Output Formatting
• Use the same techniques with file stream
  objects as with cout: showpoint,
  setw(x), showprecision(x), etc.
• Requires iomanip to use manipulators

slide 347
  12.3 Passing File Stream Objects
           to Functions
• Use pass by reference in prototype, heading:
      bool getData(ifstream &, int&);
• Use stream object in call:
      int score;
      ifstream gradeFile("grades.txt");
      if (!getData(gradeFile, score)) ...

 slide 348
              12.4 More Detailed
                 Error Testing
• Can examine error state bits to determine stream
• Bits tested/cleared by stream member functions
     ios::eofbit     set when end of file detected
     ios::failbit    set when operation failed
     ios::hardfail   set when error occurred and no recovery
     ios::badbit     set when invalid operation attempted
     ios::goodbit    set when no other bits are set

 slide 349
            Member Functions / Flags
eof()         true if eofbit set, false otherwise

fail()        true if failbit or hardfail set, false otherwise

bad()         true if badbit set, false otherwise

good()        true if goodbit set, false otherwise

clear()       clear all flags (no arguments), or clear a specific

slide 350
            12.5 Member Functions for
             Reading and Writing Files
• Functions that may be used for input with
  whitespace, to perform single character I/O,
  or to return to the beginning of an input file
• Member functions:
            getline: reads input including whitespace
            get: reads a single character
            put: writes a single character

slide 351
            getline Member Function
• Three arguments:
     – Character array to hold input
     – Number of characters to read
     – Terminator to stop at if encountered before
       number of characters was read in
     – Examples, using file object stuFile:
       stuFile.getline(name, 40, '\n');
       stuFile.getline(addr, 40, '\t');
     – '\n' is default for third argument

slide 352
                Single Character I/O
• get: read a single character from a file
            char letterGrade;
     Will read any character, including whitespace
• put: write a single character to a file

slide 353
            12.6 Working with
              Multiple Files
• Can have > 1 file open at a time in a program
• Files may be open for input or output
• Need to define file stream object for each file

slide 354
              12.7 Binary Files
• Binary file contains unformatted, non-ASCII data
• Indicate by using binary flag on open:
    inFile.open("nums.dat", ios::in |

  slide 355
                              Binary Files
• Use read and write instead of <<, >>
  char ch;
  // read in a letter from file
  inFile.read(&ch, sizeof(ch));

              address of where to put
              the data being read in.     how many bytes to
              The read function expects
                                          read from the file
              to read chars

  // send a character to a file
  outFile.write(&ch, sizeof(ch));

  slide 356
                           Binary Files
• To read, write non-character data, must use a
  typecast operator to treat the address of the data as a
  character address
   int num;
   // read in a binary number from a file
   inFile.read(reinterpret_cast<char *>&num,
   treat the address of num as
   the address of a char

   // send a binary value to a file
   outf.write(reinterpret_cast<char *>&num,
  slide 357
            12.8 Creating Records with
• Can write structures to, read structures from
• To work with structures and files,
     – use ios::binary file flag upon open
     – use read, write member functions

slide 358
  Creating Records with Structures
  struct TestScore
    int studentId;
    float score;
    char grade;
  TestScore oneTest;
  // write out oneTest to a file
  gradeFile.write(reinterpret_cast<char *>
    (&oneTest), sizeof(oneTest));
slide 359
             12.9 Random-Access Files
• Sequential access: start at beginning of file
  and go through data in file, in order, to end
    – to access 100th entry in file, go through 99
      preceding entries first
• Random access: access data in a file in any
    – can access 100th entry directly

 slide 360
             Random Access
            Member Functions
• seekg (seek get): used with files open for
• seekp (seek put): used with files open for
• Used to go to a specific position in a file

slide 361
                Random Access
               Member Functions
• seekg,seekp arguments:
   offset: number of bytes, as a long
   mode flag: starting point to compute offset
• Examples:
   inData.seekg(25L, ios::beg);
   // set read position at 26th byte
   // from beginning of file
   outData.seekp(-10L, ios::cur);
   // set write position 10 bytes
   // before current position

slide 362
              Important Note on
               Random Access
• If eof is true, it must be cleared before seekg
  or seekp:

   gradeFile.seekg(0L, ios::beg);
   // go to the beginning of the file

  slide 363
            Random Access Information
• tellg member function: return current byte
  position in input file
            long int whereAmI;
            whereAmI = inData.tellg();
• tellp member function: return current byte
  position in output file
            whereAmI = outData.tellp();

slide 364
              12.10 Opening a File for
               Both Input and Output
• File can be open for input and output simultaneously
• Supports updating a file:
   – read data from file into memory
   – update data
   – write data back to file
• Use fstream for file object definition:
       fstream gradeList("grades.dat",
             ios::in | ios::out);
• Can also use ios::binary flag for binary data
  slide 365
      Chapter 13
Introduction to Classes
13.1        Procedural and Object-Oriented Programming
13.2        Introduction to Classes
13.3        Defining an Instance of a Class
13.4        Why Have Private Members?
13.5        Software Design Considerations
13.6        Using Private Member Functions
13.7        Inline Member Functions
13.8        Constructors

slide 367
13.9 Destructors
13.10 Constructors That Accept Arguments
13.11 Input Validation Objects
13.12 Overloading Constructors
13.13 Only One Default Constructor and One Destructor
13.14 Arrays of Objects
13.18 An Object-Oriented System Development Primer

 slide 368
        13.1 Procedural and Object-
           Oriented Programming
• Procedural programming focuses on the
  process/actions that occur in a program
• Object-Oriented programming is based on
  the data and the functions that operate on it.
  Objects are instances of ADTs that represent
  the data and its functions

slide 369
            Problems with Procedural
• Use of global data may allow data corruption
• Programs based on complex function
  hierarchies are:
     – difficult to understand and maintain
     – difficult to modify and extend
     – easy to break

slide 370
      Object-Oriented Programming
• class: like a struct (allows bundling of
  related variables), but variables and
  functions in the class can have different
  properties than in a struct
• object: an instance of a class, in the same
  way that a variable can be an instance of a

slide 371
      Object-Oriented Programming
• attributes: members of a class

• methods or behaviors: member functions of a

slide 372
              More on Objects
• data hiding: restricting access to certain members
  of an object
• public interface: members of an object that are
  available outside of the object. This allows the
  object to provide access to some data and functions
  without sharing its internal details and design, and
  provides some protection from data corruption
• objects can be general-purpose or application-

slide 373
            13.2 Introduction to Classes
• Objects are created from a class
• Format:
            class <class name>

slide 374
                   Class Example
            class Square
                 int side;
                 void setSide(int s)
                 { side = s; }
                 int getSide()
                 { return side; }
slide 375
            Access Specifiers
• Used to control access to members of the
• public: can be accessed by functions
  outside of the class
• private: can only be called by or
  accessed by functions that are members of
  the class

slide 376
            More on Access Specifiers
• Can be listed in any order in a class
• Can appear multiple times in a class
• If not specified, the default is private

slide 377
      13.3 Defining an Instance of a
• An object is an instance of a class
• Defined like structure variables:
            Square sq1, sq2;
• Access members using dot operator:
            cout << sq2.getSide();
• Compiler error if attempt to access private
  member using dot operator
slide 378
            Pointer to an Object
• Can define a pointer to an object:
     Square *sqPtr;
• Can access public members via pointer:
     sqPtr = &sq1;
     sqPtr = &sq2;
     cout << sqPtr->getSide();

slide 379
13.4 Why Have Private Members?
• Making data members private provides
  data protection
• Data can be accessed only through public
• Public functions define the class’s public

slide 380
            Set vs. Get Functions
• Set function: function that stores a value in a
  private member variable
• Get function: function that retrieves a value
  from a private member variable
• Common class design practice: make all
  member variables private, provide public
  set and get functions

slide 381
              13.5 Software Design
– Place class declaration in a header file that serves as
  the class specification file. Name the file
  <classname>.h, for example, square.h
– Place member function definitions in
  <classname>.cpp, for example, square.cpp File
  should #include the class specification file
– Programs that use the class must #include the class
  specification file, and be compiled and linked with the
  member function definitions
  slide 382
            Defining a Member Function
• When defining a member function:
     – Put prototype in class declaration
     – Define function using class name and scope
       resolution operator (::)
             int Square::getSide()
                 return side;

slide 383
            Input/Output with Objects
• Class should be designed to provide
  functions to store, retrieve data
• Functions that use objects of a class should
  perform input/output operations, not class
  member functions
• Exceptions can occur: class designed to
  display a menu, or class designed specifically
  to perform I/O

slide 384
            13.6 Using Private Member
• A private member function can only be
  called by another member function
• It is used for internal processing by the class,
  not for use outside of the class

slide 385
      13.7 Inline Member Functions
• Member functions can be defined
     – inline: in class declaration
     – after the class declaration
• Inline appropriate for short function bodies:
            int getSide() { return side; }

slide 386
       Tradeoffs – Inline vs. Regular
            Member Functions
• Regular functions – when called, compiler
  stores return address of call, allocates
  memory for local variables, etc.
• Code for an inline function is copied into
  program in place of call – larger executable
  program, but no function call overhead,
  hence faster execution

slide 387
             13.8 Constructors
• Member function that is called when an object
  is created
• Called automatically
• Constructor function name is class name
• Has no return type

 slide 388
                Constructor Example
            class Square
                 Square();   // prototype
            Square::Square() // heading
                 side = 1;
slide 389
             13.9 Destructors
• Member function automatically called when an
  object is destroyed
• Destructor name is ~classname, e.g., ~Square
• Has no return type; takes no arguments
• Only 1 destructor per class, i.e., it cannot be
• If constructor allocates dynamic memory, destructor
  should release it

slide 390
    13.10 Constructors That Accept
• Default constructor: constructor that takes no
• To create an object using the default constructor,
  use no argument list and no ():
        Square square1;
• To create a constructor that takes arguments:
    – indicate parameters in prototype, definition
    – provide arguments when object is created:
        Square square2(12);
 slide 391
            Constructors That Accept
Constructor may have default arguments:
   Square(int = 1);       // prototype

   Square::Square(int s) // heading
      side = s;

slide 392
      13.11 Input Validation Objects
• Objects can be designed to validate user
     – Acceptable menu choice
     – Test score in range of valid scores
     – etc.

slide 393
    13.12 Overloading Constructors
• A class can have > 1 constructor
• Overloaded constructors in a class must have
  different parameter lists:

slide 394
      Member Function Overloading
• Non-constructor member functions can also
  be overloaded:
            void setSide();
            void setSide(int);
• Must have unique parameter lists as for

slide 395
13.13 Only One Default Constructor
       and One Destructor
• Do not provide > 1 default constructor for a
  class: one that takes no arguments and one
  that has default arguments for all parameters
            Square(int = 0);   // will not
• Since a destructor takes no arguments, there
  can only be one destructor for a class
slide 396
             13.14 Arrays of Objects
• Objects can be the elements of an array:
   Square lottaSquares[10];
• Default constructor for object is used when array is
• Must use initializer list to invoke constructor that
  takes arguments:
   Square triSqu[3] = {5,7,11};
• More complex initialization if constructor takes > 1
 slide 397
       Accessing Objects in an Array
• Objects in an array are referenced using
• Member functions are referenced using dot
   cout << triSqu[i].getSide;

 slide 398
 13.18 An Object-Oriented System
       Development Primer
• Procedural Programming:
     – program is made up of procedures: sets of
       programming statements that perform tasks
• Object-Oriented Programming:
     – program is made up of objects: entities that
       contain data (attributes) and actions (methods)

slide 399
               Benefits of
      Object-Oriented Programming
• Simplification of software development for
  graphical (GUI) applications
     – visual components (menus, text boxes, etc.)
       modeled as objects
     – visual components (e.g., windows) may be made
       up of multiple objects
     – some objects (e.g., buttons) may have methods
       associated with them

slide 400
               Benefits of
      Object-Oriented Programming
• Simplification of software development for
  non-GUI applications - the problem:
     – procedural programming enforces separation
       between code and data
     – changes in data format require extensive
       analysis, testing to ensure program functionality

slide 401
               Benefits of
      Object-Oriented Programming
• Simplification of software development for
  non-GUI applications - a solution:
     – OO programming addresses the problem through
            • encapsulation: combination of data and actions in an
            • data hiding: protection of an object’s data by its public
              member functions

slide 402
            Component Reusability
• Component: a software object that performs
  a well-defined task or that provides a service
• Component Reusability: the ability to use a
  component in multiple programs without (or
  with little) modification

slide 403
     Relationships Between Objects
• A program may contain objects of different
• Objects may be related by one of the
     – Access (‘knows’ relationship)
     – Ownership (‘has a’ relationship)
     – Inheritance (‘is a’ relationship)

slide 404
       Messages and Polymorphism
• Message: request to an object to perform a
  task. Implemented as a member function call
• Polymorphism: ability to take many forms.
  Sending the same message to different
  objects may produce different behaviors

slide 405
              Object Oriented Analysis
• Used to create the logical design of a system, what the
  system is to do
• Usually includes
  – examine the problem domain; model the system from within
    that perspective
  – identify the objects that exist within the boundaries of that
  – identify the relationships between the objects
  – realize that there may be many ‘right’ solutions

  slide 406
            Object Oriented Design
• Used to determine how requirements from
  OO Analysis will be implemented
• Usually includes
     – determine hierarchical relation between objects
     – determine object ownership of attributes
     – implement and test; refine as required

slide 407
    Chapter 14
More About Classes
14.1        Instance and Static Members
14.2        Friends of Classes
14.3        Memberwise Assignment
14.4        Copy Constructors
14.5        Operator Overloading
14.6        Object Conversion
14.8        Object Composition
slide 409
            14.1 Instance and Static
• instance variable: a member variable in a
  class. Each object has its own copy.
• static variable: one variable shared among
  all objects of a class
• static member function: can be used to
  access static member variable; can be
  called before any objects are defined

slide 410
              static member variable
1) Declare with keyword static :
            class IntVal
            { public:
                   intVal(int val = 0)
                   { value = val; valCount++; }
                   int getVal();
                   void setVal(int);
                   int value;
                   static int valCount;
slide 411
            static member variable
2) Define outside of class:
            int IntVal::valCount = 0;
3) Can be accessed or modified by any object
   of the class:
            IntVal val1, val2;
                        value                 value

slide 412
             static member function
• Declared with static before return type:
            static int getVal()
            { return valCount; }
• Can only access static member data
• Can be called independent of objects:
            cout << "There are " <<
            IntVal::getVal() << " objects\n";

slide 413
            14.2 Friends of Classes
• Friend: a function or class that is not a member
  of a class, but has access to private members of
  the class
• A friend function can be a stand-alone function
  or a member function of another class
• It is declared a friend of a class with friend
  keyword in the function prototype

slide 414
        friend Function Declarations
• Stand-alone function:
  friend void setAVal(intVal&, int);
  // declares setAVal function to be
  // a friend of this class
• Member function of another class:
  friend void SomeClass::setNum(int num)
  // setNum function from SomeClass
  // class is a friend of this class

  slide 415
 friend Function Implementation
• Body:
       void setAVal(intVal &it, int val)
            it.value = val;
• Use:
       IntVal v1(13), v2(5);
       setAVal(v2, 11);

slide 416
             friend Class Declarations
• Class as a friend of a class:
    class FriendClass
    class NewClass
        friend class FriendClass; // declares
      // entire class FriendClass as a friend
      // of this class
 slide 417
     14.3 Memberwise Assignment

• Can use = to assign one object to another, or
  to initialize an object with an object’s data
• Copies member to member. e.g.,
            v2 = v1; means:
            copy all member values from v1 and assign to
            the corresponding member variables of v2
• Use at initialization:
            IntVal v3 = v2;

slide 418
            14.4 Copy Constructors
• Special constructor used when a newly
  created object is initialized to the data of
  another object of same class
• Default copy constructor copies field-to-field
• Default copy constructor works fine in many

slide 419
             Copy Constructors
    Problem: what if object contains a pointer?
    class SomeClass
    { public:
         SomeClass(int val = 0)
            {value=new int; *value = val;}
         int getVal();
         void setVal(int);
         int *value;
slide 420
              Copy Constructors
What we get using memberwise copy with
objects containing dynamic memory:
       SomeClass object1(5);
       SomeClass object2 = object1;
       cout << object1.getVal(); // also 13
            object1             object2

                value              value

slide 421
                Copy Constructor
• Allows us to solve problem with objects containing
    SomeClass::SomeClass(SomeClass &obj)
       value = new int;
       *value = obj.value;
• Copy constructor takes a reference parameter to
  an object of the class
   slide 422
               Copy Constructor
• Each object now points to separate dynamic
         SomeClass object1(5);
         SomeClass object2 = object1;
         cout << object1.getVal(); // still 5
                           5                    13
             object1             object2

                 value              value

 slide 423
               Copy Constructor
• Since copy constructor has reference to the object
  it is copying from,
    SomeClass::SomeClass(SomeClass &obj)
  it can modify that object.
• To prevent this from happening, make the object
  parameter const:
                  (const SomeClass &obj)

  slide 424
              14.5 Operator Overloading
• Operators such as =, +, and others can be redefined
  when used with objects of a class
• The name of the function for the overloaded operator is
  operator followed by the operator symbol, e.g.,
     operator+ to overload the + operator, and
     operator= to overload the = operator
• Prototype for the overloaded operator goes in the
  declaration of the class that is overloading it
• Overloaded operator function definition goes with other
  member functions

  slide 425
             Operator Overloading
• Prototype:
void operator=(const SomeClass &rval)

                               parameter for
return       function          object on right
 type         name            side of operator

• Operator is called via object on left side
 slide 426
 Invoking an Overloaded Operator
• Operator can be invoked as a member
• It can also be used in more conventional
       object1 = object2;

slide 427
               Returning a Value
• Overloaded operator can return a value
  class Point2d
      float operator-(const point2d &right)// computes
      { return sqrt(pow((x-right.x),2) // and displays
                  + pow((y-right.y),2)); } // the
                       // distance between two points
      int x, y;
  Point2d point1(2,2), point2(4,4);
  cout << point2 – point1 << endl; // displays 2.82843
  slide 428
              Returning a Value
• Return type the same as the left operand supports
  notation like:
     object1 = object2 = object3;
• Function declared as follows:
     SomeClass operator=(const someClass &rval)
• In function, include as last statement:
       return *this;

  slide 429
            The this Pointer
• this: predefined pointer available to a
  class’s member functions
• Always points to the instance (object) of the
  class whose function is being called
• Is passed as a hidden argument to all non-
  static member functions
• Can be used to access members that may be
  hidden by parameters with same name

slide 430
            this Pointer Example
     class SomeClass
             int num;
             void setNum(int num)
             { this->num = num; }

slide 431
                       Notes on
                 Overloaded Operators
• Can change meaning of an operator
• Cannot change the number of operands of
  the operator
• Only certain operators can be overloaded.
  Cannot overload the following operators:
            ?:   .   .*   :: sizeof

slide 432
    Overloading Types of Operators
• ++, -- operators overloaded differently for
  prefix vs. postfix notation
• Overloaded relational operators should return
  a bool value
• Overloaded stream operators >>, << must
  return reference to istream, ostream
  objects and take istream, ostream objects
  as parameters

slide 433
            Overloaded [] Operator
• Can create classes that behave like arrays,
  provide bounds-checking on subscripts
• Must consider constructor, destructor
• Overloaded [] returns a reference to object,
  not an object itself

slide 434
              14.6 Object Conversion
• Type of an object can be converted to another type
• Automatically done for built-in data types
• Must write an operator function to perform
• To convert an IntVal object to an int:
            IntVal::operator int() {return value;}
• Allows statements like:
            int num; IntVal val(2);
            num = val;     // num now has 2

slide 435
            14.8 Object Composition
• Object composition: a class is a member of a
• Supports the modeling of ‘has a’ relationship
  between classes – enclosing class ‘has a’
  enclosed class
• Same notation as for structures within

slide 436
            Object Composition
  class StudentInfo
           string firstName, LastName;
           string address, city, state, zip;
  class Student
           StudentInfo personalData;
slide 437
           Chapter 15
Inheritance, Polymorphism, and
        Virtual Functions
15.1 What Is Inheritance?
15.2 Protected Members and Class Access
15.3 Constructors and Destructors
15.4 Redefining Base Class Functions
15.5 Polymorphism and Virtual Member

slide 439
15.6 Abstract Base Classes and Pure Virtual
15.7 Base Class Pointers
15.8 Classes Derived from Derived Classes
15.9 Multiple Inheritance

slide 440
            15.1 What Is Inheritance?
• Provides a way to create a new class from an
  existing class
• New class can replace or extend functionality of
  existing class
• Can be done from one (single inheritance) or
  more (multiple inheritance) classes

slide 441
      Inheritance – Terminology and
• Parent, or base class – inherited from
• Child, or derived class – inherited class
• Notation:
            class Student             // parent
             . . .
            class UnderGrad : public student
            {                         // child
             . . .
slide 442
               ‘is a’ Relation
• Inheritance models an 'is a' relation between
  classes. An object of a derived class 'is a(n)'
  object of the base class
• Example:
    – an UnderGrad is a Student
    – a Mammal is an Animal
• A derived object has all of the characteristics
  of the base class
 slide 443
            What Does a Child Have?
Object of child class has:
• all members defined in child class
• all members declared in parent class
Object of child class can use:
• all public members defined in child class
• all public members defined in parent class

slide 444
       15.2 Protected Members and
              Class Access
• protected member access specification:
  like private, but accessible by objects of
  derived class
• Class access specification: determines how
  private, protected, and public
  members of base class can be accessed by
  object of derived class

slide 445
            Class Access Specifiers
1) public – object of derived class can be
   treated as object of base class (not vice-
2) protected – more restrictive than public,
   but allows derived classes to know details of
3) private – prevents objects of derived class
   from being treated as objects of base class.

slide 446
                 Inheritance vs. Access
                                    How base class members
Base class members                   appear in derived class
 private: x           private          x is inaccessible
 protected: y         base class
                                       private: y
 public: z                             private: z

 private: x           protected         x is inaccessible
 protected: y          base class       protected: y
 public: z                              protected: z

  private: x            public          x is inaccessible
  protected: y         base class       protected: y
  public: z                             public: z

   slide 447
              More Inheritance vs. Access
         class Grade                    class Test : public Grade
private members:                     private members:
   char letter;                         int numQuestions;
   float score;                         float pointsEach;
   void calcGrade();                    int numMissed;
public members:                      public members:
   void setScore(float);                Test(int, int);
   float getScore();
   char getLetter();
                                     private members:
                                        int numQuestions:
     When Test class inherits           float pointsEach;
     from Grade class using             int numMissed;
     public class access, it looks   public members:
                                        Test(int, int);
     like this:                         void setScore(float);
                                        float getScore();
                                        float getLetter();

  slide 448
      More Inheritance vs. Access (2)
         class Grade               class Test : protected Grade
private members:                  private members:
   char letter;                      int numQuestions;
   float score;                      float pointsEach;
   void calcGrade();                 int numMissed;
public members:                   public members:
   void setScore(float);             Test(int, int);
   float getScore();
   char getLetter();
                                  private members:
                                     int numQuestions:
     When Test class inherits        float pointsEach;
     from Grade class using          int numMissed;
     protected class access, it   public members:
                                     Test(int, int);
     looks like this:             protected members:
                                     void setScore(float);
                                     float getScore();
                                     float getLetter();

  slide 449
      More Inheritance vs. Access (3)
         class Grade                    class Test : private Grade
private members:                      private members:
   char letter;                          int numQuestions;
   float score;                          float pointsEach;
   void calcGrade();                     int numMissed;
public members:                       public members:
   void setScore(float);                 Test(int, int);
   float getScore();
   char getLetter();
                                      private members:
                                         int numQuestions:
     When Test class inherits            float pointsEach;
     from Grade class using              int numMissed;
     private class access, it looks      void setScore(float);
                                         float getScore();
     like this:                          float getLetter();
                                      public members:
                                         Test(int, int);

  slide 450
            15.3 Constructors and
• Derived classes can have their own
  constructors and destructors
• When an object of a derived class is created,
  the base class’s constructor is executed first,
  followed by the derived class’s constructor
• When an object of a derived class is
  destroyed, its destructor is called first, then
  that of the base class

slide 451
        Constructors and Destructors
      // Student –    base class
      // UnderGrad    – derived class
      // Both have    constructors, destructors
      int main()
                                   Execute Student constructor,
      {                            then execute UnderGrad
         UnderGrad   u1;           constructor

            return 0;
      }       // end main
                                    Execute UnderGrad
                                    destructor, then execute
                                    Student destructor
slide 452
              Passing Arguments to
             Base Class Constructor
• Allows selection between multiple base class
• Specify arguments to base constructor on
  derived constructor heading:
      Square::Square(int side) :
           Rectangle(side, side)
• Can also be done with inline constructors
• Must be done if base class has no default
 slide 453
               Passing Arguments to
              Base Class Constructor

      derived class constructor               base class constructor

Square::Square(int side):Rectangle(side,side)

                        derived constructor             base constructor
                        parameter                       parameters

  slide 454
            15.4 Redefining Base Class
• Redefining function: function in a derived
  class that has the same name and parameter
  list as a function in the base class
• Also called overriding function
• Typically used to replace a function in base
  class with different actions in derived class

slide 455
  Redefining Base Class Functions
• Not the same as overloading – with
  overloading, parameter lists must be different
• Objects of base class use base class version
  of function; objects of derived class use
  derived class version of function

slide 456
             Problem with Redefining
• Consider this situation:
    – Class BaseClass defines functions X() and Y().
      X() calls Y().
    – Class DerivedClass inherits from BaseClass and
      redefines function Y().
    – An object D of class DerivedClass is created and
      function X() is called.
    – When X() is called, which Y() is used, the one
      defined in BaseClass or the the redefined one in

 slide 457
            Problem with Redefining

   void X();           Object D invokes function X()
   void Y();           In BaseClass. Function X()
                       invokes function Y() in BaseClass,
  DerivedClass         not function Y() in DerivedClass,
                       because function calls are bound
                       at compile time. This is static binding.

   void Y();

   DerivedClass D;

slide 458
     15.5 Polymorphism and Virtual
          Member Functions
• Virtual member function: function in base class
  that expects to be redefined in derived class
• Function defined with key word virtual:
    virtual void Y() {...}
• Supports dynamic binding: functions bound at
  run time to function that they call
• Without virtual member functions, C++ uses
  static (compile time) binding

slide 459
         Solution to Problem with
                       Object D invokes function X()
   void X();           In BaseClass. Function X()
   virtual void Y();   invokes function Y() in
                       DerivedClass, not function Y() in
  DerivedClass         BaseClass. Function Y() is virtual,
                       so calls are bound at execution time.
                       This is static binding.

   void Y();

   DerivedClass D;

slide 460
   13.6 Abstract Base Classes and
        Pure Virtual Functions
• Pure virtual function: a virtual member function
  that must be redefined in a derived class that
  has objects
• Abstract base class contains at least one pure
  virtual function:
      virtual void Y() = 0;
• The = 0 indicates a pure virtual function
• Must have no function definition in the base
 slide 461
    Abstract Base Classes and Pure
           Virtual Functions
• Abstract base class: class that can have no
  objects. Serves as a basis for derived classes
  that may/will have objects
• A class becomes an abstract base class when
  one or more of its member functions is a pure
  virtual function

 slide 462
            15.7 Base Class Pointers
• Can define a pointer to a base class object
• Can assign it the address of a derived class
• Redefined functions in derived class will be
  ignored unless base class declares the
  function virtual

slide 463
               Base Class Pointers

                       objPtr is a pointer to a BaseClass
   void X();           object. D is a DerivedClass object.
                       objPtr points to D. When function X()
   void Y();           is invoked via objPtr, it calls the
                       version of Y()defined in BaseClass,
  DerivedClass         since objPtr is a BaseClass pointer.
                       If function Y()is a virtual function,
                        then the DerivedClass version of
                       Y() would be used instead.
   void Y();
   BaseClass objPtr;
   DerivedClass D;
   objPtr = &D;
   objPtr ->X();
slide 464
            15.8 Classes Derived from
                 Derived Classes
• A base class can be derived from      class A
  another class. A child class can be
  a base class to another child class
• Access specification between each     class B

  parent – child determines
  accessibility of members              class C

slide 465
             15.9 Multiple Inheritance
• A derived class can have > 1 base class
• Each base class can have its own access
  specification in derived class's definition:
       class cube : public square,
                     public rectSolid;
                   class            class
                   square           rectSolid

 slide 466
                 Multiple Inheritance
• Arguments can be passed to both base
  classes' constructors:
            cube::cube(int side) : square(side),
                 rectSolid(side, side, side);
• Base class constructors are called in order
  given in class declaration, not in order used
  in class constructor

slide 467
               Multiple Inheritance
• Problem: what if base classes have member
  variables/functions with the same name?
• Solutions:
   – Derived class redefines the multiply-defined function
   – Derived class invokes member function in a particular base
     class using scope resolution operator ::
• Compiler errors occur if derived class uses base class
  function without one of these solutions

 slide 468
          Chapter 16
Exceptions, Templates, and the
Standard Template Library (STL)
16.1 Exceptions
16.2 Function Templates
16.3 Where to Start When Defining Templates
16.4 Class Templates
16.5 Introduction to the Standard Template

slide 470
            16.1 Exceptions
• Indicate that something unexpected has
  occurred or been detected
• Allow program to deal with the problem in a
  controlled manner
• Can be as simple or complex as program
  design requires

slide 471
            Exceptions - Terminology
• Exception: object or value that signals an
• Throw an exception: send a signal that an
  error has occurred
• Catch/Handle an exception: process the
  exception; interpret the signal

slide 472
             Exceptions – Key Words
• throw – followed by an argument, is used to
  throw an exception
• try – followed by a block { }, is used to
  invoke code that throws an exception
• catch – followed by a block { }, is used to
  detect and process exceptions thrown in
  preceding try block. Takes a parameter that
  matches the type thrown.

 slide 473
              Exceptions – Flow of Control
1) A function that throws an exception is called from
   within a try block
2) If the function throws an exception, the function
   terminates and the try block is immediately exited. A
   catch block to process the exception is searched for
   in the source code immediately following the try
3) If a catch block is found that matches the exception
   thrown, it is executed. If no catch block that matches
   the exception is found, the program terminates.

  slide 474
            Exceptions – Example (1)
// function that throws an exception
int totalDays(int days, int weeks)
   if ((days < 0) || (days > 7))
     throw "invalid number of days";
// the argument to throw is the
// character string
     return (7 * weeks + days);
slide 475
            Exceptions – Example (2)
try // block that calls function
    totDays = totalDays(days, weeks);
   cout << "Total days: " << days;
catch (char *msg) // interpret
              // exception
   cout << "Error: " << msg;
slide 476
            Exceptions – What Happens
1)  try block is entered. totalDays function is
2) If 1st parameter is between 0 and 7, total number
   of days is returned and catch block is skipped
   over (no exception thrown)
3) If exception is thrown, function and try block are
   exited, catch blocks are scanned for 1st one that
   matches the data type of the thrown exception.
   catch block executes
slide 477
             Exceptions - Notes
• Predefined functions such as new may throw
• The value that is thrown does not need to be
  used in catch block.
     – in this case, no name is needed in catch
       parameter definition
     – catch block parameter definition does need the
       type of exception being caught
slide 478
            Exception Not Caught?
• An exception will not be caught if
     – it is thrown from outside of a try block
     – there is no catch block that matches the data
       type of the thrown exception
• If an exception is not caught, the program will

slide 479
            Exceptions and Objects
• An exception class can be defined in a class
  and thrown as an exception by a member
• An exception class may have:
     – no members: used only to signal an error
     – members: pass error data to catch block
• A class can have > 1 exception class

slide 480
  Exceptions – What Happens After
           catch Block?
• Once an exception is thrown, the program cannot
  return to throw point. The function executing
  throw terminates (does not return), other calling
  functions in try block terminate, resulting in
  unwinding the stack
• If objects were created in the try block and an
  exception is thrown, they are destroyed.

  slide 481
                 Nested try Blocks
•   try/catch blocks can occur within an
    enclosing try block
• Exceptions caught at an inner level can be
  passed up to a catch block at an outer level:
            catch ( )
               throw; // pass exception up
            }         // to next level
slide 482
            16.2 Function Templates
• Function template: a pattern for a function
  that can work with many data types
• When written, parameters are left for the data
• When called, compiler generates code for
  specific data types in function call

slide 483
            Function Template Example
     template <class T>                                    prefix
     T times10(T num)                                      generic
     {                                                    data type
             return 10 * num;
     }                                                  parameter
 What gets generated when         What gets generated when times10
 times10 is called with an int:   is called with a float:
 int times10(int num)             float times10(float num)
 {                                {
    return 10 * num;                   return 10 * num;
 }                                }
slide 484
              Function Template Example
  template <class T>
  T times10(T num)
          return 10 * num;
• Call a template function in the usual manner:
     int ival = 3;
     float fval = 2.55;
     cout << times10(ival); // displays 30
     cout << times10(fval); // displays 25.5
  slide 485
                  Function Template Notes
• Can define a template to use multiple data types:
       template<class T1, class T2>
• Example:
  template<class T1, class T2>    // T1 and T2 will be
  double mpg(T1 miles, T2 gallons) // replaced in the
  {                               // called function
      return miles / gallons      // with the data
  }                               // types of the
                                   // arguments

      slide 486
             Function Template Notes
• Function templates can be overloaded Each
  template must have a unique parameter list
       template <class T>
       T sumAll(T num) ...
       template <class T1, class T2>
       T1 sumall(T1 num1, T2 num2) ...

 slide 487
             Function Template Notes
• All data types specified in template prefix must
  be used in template definition
• Function calls must pass parameters for all
  data types specified in the template prefix
• Like regular functions, function templates must
  be defined before being called

 slide 488
             Function Template Notes
• A function template is a pattern
• No actual code is generated until the function
  named in the template is called
• A function template uses no memory
• When passing a class object to a function
  template, ensure that all operators in the
  template are defined or overloaded in the class
 slide 489
              16.3 Where to Start
            When Defining Templates
• Templates are often appropriate for multiple
  functions that perform the same task with
  different parameter data types
• Develop function using usual data types first,
  then convert to a template:
     – add template prefix
     – convert data type names in the function to a type
       parameter (i.e., a T type) in the template
slide 490
            16.4 Class Templates
• Classes can also be represented by
  templates. When a class object is created,
  type information is supplied to define the type
  of data members of the class.
• Unlike functions, classes are instantiated by
  supplying the type name (int, float,
  string, etc.) at object definition

slide 491
            Class Template Example
     template <class T>
     class grade
             T score;
             void setGrade(T);
             T getGrade()
slide 492
              Class Template Example
• Pass type information to class template when
  defining objects:
            grade<int> testList[20];
            grade<float> quizList[20];

• Use as ordinary objects once defined

slide 493
               Class Templates
               and Inheritance
• Class templates can inherit from other class
    template <class T>
    class Rectangle
      { ... };
    template <class T>
    class Square : public Rectangle<T>
      { ... };
• Must use type parameter T everywhere base class
  name is used in derived class
 slide 494
 16.5 Introduction to the Standard
         Template Library
• Standard Template Library (STL): a library
  containing templates for frequently used data
  structures and algorithms
• Not supported by many older compilers

slide 495
            Standard Template Library
• Two important types of data structures in the
     – containers: classes that stores data and imposes
       some organization on it
     – iterators: like pointers; mechanisms for accessing
       elements in a container

slide 496
• Two types of container classes in STL:
    – sequence containers: organize and access data
      sequentially, as in an array. These include
      vector, dequeue, and list
    – associative containers: use keys to allow data
      elements to be quickly accessed. These include
      set, multiset, map, and multimap

slide 497
• Generalization of pointers, used to access
  information in containers
• Four types:
    – forward (uses ++)
    – bidirectional (uses ++ and -- )
    – random-access
    – input (can be used with cin and istream
    – output (can be used with cout and ostream
slide 498
• STL contains algorithms implemented as
  function templates to perform operations on
• Requires algorithm header file
• algorithm includes
            binary_search   count
            for_each        find
            find_if         max_element
            min_element     random_shuffle
            sort            and others
slide 499
Chapter 17
Linked Lists
17.1 Introduction to the Linked List ADT
17.2 Linked List Operations
17.3 A Linked List Template
17.4 Variations of the Linked List
17.5 The STL list Container

slide 501
      17.1 Introduction to the Linked
                 List ADT
• Linked list: set of data structures (nodes) that
  contain references to other data structures



 slide 502
                    Introduction to the
                     Linked List ADT
    • References may be addresses or array indices
    • Data structures can be added to or removed
      from the linked list during execution

head                                               NULL
        slide 503
              Linked Lists vs. Arrays and
  • Linked lists can grow and shrink as needed,
    unlike arrays, which have a fixed size
  • Linked lists can insert a node between other
    nodes easily


  slide 504
              Node Organization
• A node contains:
     – data: one or more data fields – may be organized
       as structure, object, etc.
     – a pointer that can point to another node


slide 505
             Linked List Organization
 • Linked list contains 0 or more nodes:



 • Has a list head to point to first node
 • Last node points to NULL
 slide 506
                    Empty List
• If a list currently contains 0 nodes, it is the
  empty list
• In this case the list head points to NULL

 slide 507
                  Declaring a Node
• Declare a node:
            struct ListNode
                 int data;
                 ListNode *next;
• No memory is allocated at this time

slide 508
                   Defining a Linked List
• Define a pointer for the head of the list:
            ListNode *head = NULL;
• Head pointer initialized to NULL to indicate an
  empty list


slide 509
                    NULL Pointer
• Is used to indicate end-of-list
• Should always be tested for before using a
            ListNode *p;
            while (p != NULL) ...
• Can also test the pointer itself:
            while (!p) ... // same meaning
                           // as above
slide 510
            17.2 Linked List Operations
• Basic operations:
     – append a node to the end of the list
     – insert a node within the list
     – traverse the linked list
     – delete a node
     – delete/destroy the list

slide 511
                Create a New Node
• Allocate memory for the new node:
    newNode = new ListNode;

• Initialize the contents of the node:             newNode

    newNode->value = num;
• Set the pointer field to NULL:         newNode

    newNode->next = NULL;
                                         23             NULL
    slide 512
                    Appending a Node
• Add a node to the end of the list
• Basic process:
     – Create the new node (as already described)
     – Add node to the end of the list:
            • If list is empty, set head pointer to this node
            • Else,
                 – traverse the list to the end
                 – set pointer of last node to point to new node

slide 513
                   Appending a Node

               5             13              19       NULL

                      23             NULL


              New node created, end of list located

  slide 514
                   Appending a Node

               5            13                19

                      23             NULL


              New node added to end of list

  slide 515
            Inserting a Node into a
                   Linked List
• Used to maintain a linked list in order
• Requires two pointers to traverse the list:
     – pointer to locate the node with data value greater
       than that of node to be inserted
     – pointer to 'trail behind' one node, to point to node
       before point of insertion
• New node is inserted between the nodes
  pointed at by these pointers
slide 516
               Inserting a Node into a
                      Linked List
                                        previousNode       nodePtr

               5             13              19            NULL

                      17             NULL


              New node created, correct position located

  slide 517
                Inserting a Node into a
                       Linked List
                                          previousNode        nodePtr

               5              13               19             NULL


              New node inserted in order in the linked list

  slide 518
              Traversing a Linked List
• Visit each node in a linked list: display contents,
  validate data, etc.
• Basic process:
   – set a pointer to the contents of the head pointer
   – while pointer is not NULL
         • process data
         • go to the next node by setting the pointer to the pointer field
           of the current node in the list
   – end while

  slide 519
              Traversing a Linked List

              5           13              19             NULL


     nodePtr points to the node containing 5, then the
     node containing 13, then the node containing 19,
     then points to NULL, and the list traversal stops

  slide 520
            Deleting a Node
• Used to remove a node from a linked list
• If list uses dynamic memory, then delete
  node from memory
• Requires two pointers: one to locate the node
  to be deleted, one to point to the node before
  the node to be deleted

slide 521
                     Deleting a Node

 previousNode         nodePtr

               5            13              19   NULL


              Locating the node containing 13

  slide 522
                      Deleting a Node

 previousNode          nodePtr

               5             13              19           NULL


        Adjusting pointer around the node to be deleted

  slide 523
                    Deleting a Node

 previousNode        nodePtr

              5                              19          NULL


     Linked list after deleting the node containing 13

  slide 524
            Destroying a Linked List
• Must remove all nodes used in the list
• To do this, use list traversal to visit each node
• For each node,
     – Unlink the node from the list
     – If the list uses dynamic memory, then free the node’s
• Set the list head to NULL

slide 525
            17.3 A Linked List Template
• When declaring a linked list, must specify the
  type of data to be held in each node
• Using templates, can declare a linked list that
  can hold data type determined at list
  definition time

slide 526
               17.4 Variations of the
                    Linked List
  • Other linked list organizations:
        – doubly-linked list: each node contains two
          pointers: one to the next node in the list, one to
          the previous node in the list

              5            13             19           NULL

head              NULL

  slide 527
                    Variations of the
                      Linked List
  • Other linked list organizations:
        – circular linked list: the last node in the list points
          back to the first node in the list, not to NULL

              5             13              19


  slide 528
            17.5 The STL list Container

• Template for a doubly linked list
• Member functions for
   – locating beginning, end of list: front, back,
   – adding elements to the list: insert, merge,
     push_back, push_front
   – removing elements from the list: erase,
     pop_back, pop_front, unique

slide 529
    Chapter 18
Stacks and Queues
18.1 Introduction to the Stack ADT
18.2 Dynamic Stacks
18.3 The STL stack container
18.4 Introduction to the Queue ADT
18.5 Dynamic Queues
18.6 The STL deque and queue Containers

slide 531
            18.1 Introduction to the
                  Stack ADT
• Stack: a LIFO (last in, first out) data structure
• Examples:
     – plates in a cafeteria
     – return addresses for function calls
• Implementation:
     – static: fixed size, implemented as array
     – dynamic: variable size, implemented as linked list

slide 532
                Stack Operations
                 and Functions
• Operations:
  – push: add a value onto the top of the stack
  – pop: remove a value from the top of the stack
• Functions:
  – isFull: true if the stack is currently full, i.e., has no
    more space to hold additional elements
  – isEmpty: true if the stack currently contains no
  slide 533
               Stack Operations - Example
   • A stack that can hold char values:

                                  K                K
push('E');           push('K');       push('G');
                 E                E                E

   slide 534
                Stack Operations - Example
    • A stack that can hold char values:

pop();                pop();           pop();
(remove G)        E   (remove K)   E   (remove E)

    slide 535
            18.2 Dynamic Stacks
• Grow and shrink as necessary
• Can't ever be full as long as memory is
• Implemented as a linked list

slide 536
            Implementing a Stack
• Programmers can program their own routines
  to implement stack functions
• Can also use the implementation of stack
  available in the STL

slide 537
                 18.3 The STL
                stack container
• Stack template can be implemented as a
  vector, a linked list, or a deque
• Implements push, pop, and empty member
• Implements other member functions:
     – size: number of elements on the stack
     – top: reference to element on top of the stack

slide 538
                Defining a Stack
• Defining a stack of chars, named cstack,
  implemented using a vector:
   stack< char, vector<char> > cstack;
• implemented using a list:
   stack< char, list<char> > cstack;
• implemented using a deque:
   stack< char > cstack;
• Spaces are required between consecutive >>, <<

  slide 539
       18.4 Introduction to the Queue
• Queue: a FIFO (first in, first out) data structure.
• Examples:
   – people in line at the theatre box office
   – print jobs sent to a printer
• Implementation:
   – static: fixed size, implemented as array
   – dynamic: variable size, implemented as linked list

  slide 540
             Queue Locations
             and Operations
• rear: position where elements are added
• front: position from which elements are
• enqueue: add an element to the rear of the
• dequeue: remove an element from the front of
  a queue

 slide 541
          Queue Operations - Example
• A currently empty queue that can hold char values:

• enqueue('E');




  slide 542
            Queue Operations - Example
    • enqueue('K');
                E   K
    • enqueue('G');

                E   K   G

    slide 543
            Queue Operations - Example
    • dequeue(); // remove E
                K   G
    • dequeue(); // remove K


    slide 544
             dequeue Issue, Solutions
• When removing an element from a queue,
  remaining elements must shift to front
• Solutions:
  – Let front index move as elements are removed
    (works as long as rear index is not at end of array)
  – Use above solution, and also let rear index "wrap
    around" to front of array, treating array as circular
    instead of linear (more complex enqueue, dequeue

 slide 545
            18.5 Dynamic Queues
• Like a stack, a queue can be implemented
  using a linked list
• Allows dynamic sizing, avoids issue of
  shifting elements or wrapping indices

            front              rear

slide 546
            Implementing a Queue
• Programmers can program their own routines
  to implement queue operations
• Can also use the implementation of queue
  and dequeue available in the STL

slide 547
             18.6 The STL deque
             and queue Containers
• deque: a double-ended queue. Has member
  functions to enqueue (push_back) and dequeue
• queue: container ADT that can be used to
  provide queue as a vector, list, or deque. Has
  member functions to enque (push) and dequeue

 slide 548
             Defining a Queue
• Defining a queue of chars, named cQueue,
  implemented using a deque:
  deque<char> cQueue;
• implemented using a queue:
  queue<char> cQueue;
• implemented using a list:
  queue< char, list<char> > cQueue;
• Spaces are required between consecutive >>,
  << symbols
 slide 549
Chapter 19
19.1        Introduction to Recursion
19.2        The Recursive Factorial Function
19.3        The Recursive gcd Function
19.4        Solving Recursively Defined Problems

slide 551
19.5        Recursive Linked List Operations
19.6        A Recursive Binary Search Function
19.7        The QuickSort Algorithm
19.8        Exhaustive Algorithms
19.9        Recursion Versus Iteration

slide 552
     19.1 Introduction to Recursion
• A recursive function contains a call to itself:
     void countDown(int num)
        if (num == 0)
           cout << "Blastoff!";
           cout << num << "...\n";
           countDown(num-1); // recursive
        }                    // call
slide 553
          What Happens When Called?
If a program contains a line like countDown(2);
1. countDown(2) generates the output 2..., then it calls
2. countDown(1) generates the output 1..., then it calls
3. countDown(0) generates the output Blastoff!, then
    returns to countDown(1)
4. countDown(1) returns to countDown(2)
5. countDown(2)returns to the calling function
   slide 554
      What Happens When Called?
                first call to
                num is 2                                         output:

                                second call to
                                num is 1
                                                 third call to
                                                 num is 0
                                          // no                  Blastoff!
                                          // recursive
                                          // call
slide 555
    Recursive Functions - Purpose
• Recursive functions are used to reduce a
  complex problem to a simpler-to-solve
• The simpler-to-solve problem is known as the
  base case
• Recursive calls stop when the base case is

slide 556
            Stopping the Recursion
• A recursive function must always include a
  test to determine if another recursive call
  should be made, or if the recursion should
  stop with this call
• In the sample program, the test is:
      if (num == 0)

slide 557
            Stopping the Recursion
     void countDown(int num)
        if (num == 0) // test
           cout << "Blastoff!";
           cout << num << "...\n";
           countDown(num-1); // recursive
        }                    // call

slide 558
            Stopping the Recursion
• A different value is passed to the function
  each time it is called
• Eventually, the parameter reaches the value
  in the test, and the recursion stops

slide 559
            Stopping the Recursion
void countDown(int num)
   if (num == 0)
      cout << "Blastoff!";
      cout << num << "...\n";
      countDown(num-1);// note that the value
   }                   // passed to recursive
}                      // calls decreases by
                       // one for each call
slide 560
        What Happens When Called?
• Each time a recursive function is called, a new
  copy of the function runs, with new instances
  of parameters and local variables created
• As each copy finishes executing, it returns to
  the copy of the function that called it
• When the initial copy finishes executing, it
  returns to the part of the program that made
  the initial call to the function
 slide 561
           What Happens When Called?
                     first call to
                     num is 2                                         output:

                                     second call to
return                               countDown
                                     num is 1
                                                      third call to
                return                                countDown
                                                      num is 0
                                               // no                  Blastoff!
                                               // recursive
                                               // call
    slide 562
               Types of Recursion
• Direct
     – a function calls itself
• Indirect
     – function A calls function B, and function B calls
       function A
     – function A calls function B, which calls …, which
       calls function A

slide 563
         19.2 The Recursive Factorial
• The factorial function:
   n! = n*(n-1)*(n-2)*...*3*2*1 if n > 0
   n! = 1 if n = 0
• Can compute factorial of n if the factorial of (n-
  1) is known:
   n! = n * (n-1)!
• n = 0 is the base case

  slide 564
  The Recursive Factorial Function
 int factorial (int num)
   if (num > 0)
     return num * factorial(num - 1);
     return 1;

slide 565
 19.3 The Recursive gcd Function
• Greatest common divisor (gcd) is the largest
  factor that two integers have in common
• Computed using Euclid's algorithm:
     gcd(x, y) = y if y divides x evenly
     gcd(x, y) = gcd(y, x % y) otherwise
• gcd(x, y) = y is the base case

slide 566
            The Recursive gcd Function
     int gcd(int x, int y)
        if (x % y == 0)
           return y;
           return gcd(y, x % y);

slide 567
 19.4 Solving Recursively Defined
• The natural definition of some problems leads
  to a recursive solution
• Example: Fibonacci numbers:
            0, 1, 1, 2, 3, 5, 8, 13, 21, ...
• After the starting 0, 1, each number is the
  sum of the two preceding numbers
• Recursive solution:
     fib(n) = fib(n – 1) + fib(n – 2);
• Base cases: n <= 0, n == 1
slide 568
            Solving Recursively Defined
int fib(int n)
   if (n <= 0)
      return 0;
   else if (n == 1)
      return 1;
        return fib(n – 1) + fib(n – 2);

slide 569
            19.5 Recursive Linked List
• Recursive functions can be members of a
  linked list class
• Some applications:
     – Compute the size of (number of nodes in) a list
     – Traverse the list in reverse order

slide 570
             Size of a Linked List
• Uses a pointer to visit each node
• Algorithm:
     – pointer starts at head of list
     – If pointer is NULL, return 0 (base case)
       else, return 1 + number of nodes in the list
       pointed to by current node

slide 571
               Contents of a List
               in Reverse Order
• Algorithm:
     – pointer starts at head of list
     – If the pointer is NULL, return (base case)
     – If the pointer is not NULL, advance to next node
     – Upon returning from recursive call, display
       contents of current node

slide 572
   19.6 A Recursive Binary Search
• Binary search algorithm can easily be written to use
• Base cases: desired value is found, or no more
  array elements to search
• Algorithm (array in ascending order):
     – If middle element of array segment is desired value, then
     – Else, if the middle element is too large, repeat binary
       search in first half of array segment
     – Else, if the middle element is too small, repeat binary
       search on the second half of array segment

slide 573
      19.7 The QuickSort Algorithm
• Recursive algorithm that can sort an array or
  a linear linked list
• Determines an element/node to use as pivot
  value:               pivot

            sublist 1         sublist 2

slide 574
            The QuickSort Algorithm
                          pivot value

              sublist 1                 sublist 2

• Once pivot value is determined, values are
  shifted so that elements in sublist1 are <
  pivot and elements in sublist2 are > pivot
• Algorithm then sorts sublist1 and sublist2
• Base case: sublist has size 1
slide 575
 19.8 Exhaustive and Enumeration
• Exhaustive algorithm: search a set of
  combinations to find an optimal one
     Example: change for a certain amount of money
      that uses the fewest coins
• Uses the generation of all possible
  combinations when determining the optimal

slide 576
               19.9 Recursion vs. Iteration
• Benefits (+), disadvantages(-) for recursion:
  + Models certain algorithms most accurately
  + Results in shorter, simpler functions
  – May not execute very efficiently
• Benefits (+), disadvantages(-) for iteration:
  + Executes more efficiently than recursion
  – Often is harder to code or understand

   slide 577
 Chapter 20
Binary Trees
20.1 Definition and Application of Binary Trees
20.2 Binary Search Tree Operations
20.3 Template Considerations for Binary
  Search Trees

slide 579
 20.1 Definition and Application of
           Binary Trees
• Binary tree: a nonlinear linked list in which
  each node may point to 0, 1, or two other
• Each node contains
  one or more
  data fields and
                               NULL            NULL
  two pointers
                    NULL    NULL     NULL    NULL
slide 580
            Binary Tree Terminology
• Tree pointer: like a
  head pointer for a
  linked list, it points to
  the first node in the
  binary tree
• Root node: the node
  at the top of the tree
                                   NULL             NULL

                         NULL   NULL      NULL   NULL
slide 581
            Binary Tree Terminology
• Leaf nodes: nodes
  that have no children

    The nodes                  19                       59
    containing 7 and
                           7           NULL        43           NULL
    43 are leaf nodes
                        NULL        NULL        NULL         NULL

slide 582
            Binary Tree Terminology
• Child nodes, children:
  nodes below a given
  node                                   31

  The children of the        19                       59
  node containing 31
                         7                       43           NULL
  are the nodes                      NULL

  containing 19 and NULL          NULL        NULL         NULL

slide 583
            Binary Tree Terminology
• Parent node: node
  above a given node

    The parent of the         19                       59
    node containing 43
                          7           NULL        43           NULL
    is the node
    containing 59      NULL        NULL        NULL         NULL

slide 584
            Binary Tree Terminology
• Subtree: the portion of a
  tree from a node down
  to the leaves

    The nodes containing           19                       59
    19 and 7 are the left                                           NULL
                               7           NULL        43
    subtree of the node
    containing 31           NULL        NULL        NULL         NULL

slide 585
              Uses of Binary Trees
• Binary search tree: data
  organized in a binary
  tree to simplify searches
• Left subtree of a node                         31
  contains data values <
                                     19                       59
  the data in the node
• Right subtree of a node        7           NULL        43           NULL
  contains values > the
                              NULL        NULL        NULL         NULL
  data in the node

  slide 586
               Searching in a Binary Tree
1) Start at root node
2) Examine node data:
  a) Is it desired value? Done
  b) Else, is desired data < node
     data? Repeat step 2 with left                    31
  c) Else, is desired data > node           19                         59
     data? Repeat step 2 with
     right subtree
                                       7            NULL          43           NULL
3) Continue until desired
   value found or NULL               NULL    NULL          NULL         NULL
   pointer reached

   slide 587
            Searching in a Binary Tree
To locate the node
containing 43,
–   Examine the root node (31)
–   Since 43 > 31, examine
    the right child of the node                    31
    containing 31, (59)
–   Since 43 < 59, examine               19                         59
    the left child of the node
    containing 59, (43)             7                          43           NULL
–   The node containing 43 has
    been found                    NULL    NULL          NULL         NULL

slide 588
            20.2 Binary Search Tree
• Create a binary search tree – organize data
  into a binary search tree
• Insert a node into a binary tree – put node into
  tree in its correct position to maintain order
• Find a node in a binary tree – locate a node
  with particular data value
• Delete a node from a binary tree – remove a
  node and adjust links to maintain binary tree
slide 589
            Binary Search Tree Node
• A node in a binary tree is like a node in a
  linked list, with two node pointer fields:
     struct TreeNode
       int value;
       TreeNode *left;
       TreeNode *right;
slide 590
            Creating a New Node
• Allocate memory for new node:
     newNode = new TreeNode;
• Initialize the contents of the node:               newNode

     newNode->value = num;
• Set the pointers to NULL:
     newNode->Left                                   newNode
     = newNode->Right
     = NULL;                                23

                                         NULL          NULL
slide 591
              Inserting a Node in a Binary
                      Search Tree
1) If tree is empty, insert the new node as the root
2) Else, compare new node against left or right
   child, depending on whether data value of new
   node is < or > root node
3) Continue comparing and choosing left or right
   subtree until NULL pointer found
4) Set this NULL pointer to point to new node

  slide 592
             Inserting a Node in a Binary
    Examine this node first –
                              Search Tree newNode

    value is < node, so go to left
    subtree                           root                                23

Examine this node                                                     NULL     NULL
second – value is >
node, so go to right             31
                       19                     59

                  7            NULL      43            NULL

          NULL          NULL          NULL         NULL

                                             Since the right subtree is
                                             NULL, insert here
      slide 593
              Traversing a Binary Tree
       Three traversal methods:
     1) Inorder:
            a) Traverse left subtree of node
            b) Process data in node
            c) Traverse right subtree of node
     2) Preorder:
            a) Process data in node
            b) Traverse left subtree of node
            c) Traverse right subtree of node
     3) Postorder:
            a) Traverse left subtree of node
            b) Traverse right subtree of node
            c) Process data in node
slide 594
               Traversing a Binary Tree
                                                   TRAVERSAL   NODES VISITED
                                                   METHOD      IN ORDER

                                                   Inorder     7, 19, 31, 43,
          19                        59

                                                   Preorder    31, 19, 7, 59,
    7                NULL      43           NULL
NULL          NULL          NULL         NULL
                                                   Postorder   7, 19, 43, 59,

  slide 595
              Searching in a Binary Tree
• Start at root node,
  traverse the tree                     31

  looking for value           19                      59
• Stop when value
                          7                      43           NULL
  found or NULL                       NULL

  pointer detected    NULL     NULL          NULL          NULL

• Can be implemented           Search for 43? return true
  as a bool function           Search for 17? return false

  slide 596
             Deleting a Node from a
             Binary Tree – Leaf Node
• If node to be deleted is a leaf node, replace
  parent node’s pointer to it with a NULL pointer,
  then delete the node

                                     NULL         NULL
      7             NULL

NULL         NULL

 Deleting node with 7 –         Deleting node with 7 –
 before deletion                after deletion
slide 597
            Deleting a Node from a
            Binary Tree – One Child
 • If node to be deleted has one child node,
   adjust pointers so that parent of node to be
   deleted points to child of node to be deleted,
   then delete the node

slide 598
                     Deleting a Node from a
                     Binary Tree – One Child
                      31                                        31

          19                        59                7                         59

                                                   NULL       NULL
   7                NULL       43           NULL                           43           NULL

NULL         NULL          NULL          NULL                          NULL          NULL

         Deleting node with 19 –                          Deleting node with 19 –
         before deletion                                  after deletion

       slide 599
              Deleting a Node from a
            Binary Tree – Two Children
 • If node to be deleted has left and right children,
      – ‘Promote’ one child to take the place of the deleted
      – Locate correct position for other child in subtree of
        promoted child
 • Convention in text: promote the right child,
   position left subtree underneath

slide 600
                     Deleting a Node from a
                   Binary Tree – Two Children
                      31                                                     59

          19                        59                         43                    NULL

                                                          19               NULL
   7                NULL       43           NULL

NULL         NULL          NULL          NULL         7             NULL

                                                   NULL    NULL
         Deleting node with 31 –                           Deleting node with 31 –
         before deletion                                   after deletion

       slide 601
20.3 Template Considerations for
      Binary Search Trees
• Binary tree can be implemented as a
  template, allowing flexibility in determining
  type of data stored
• Implementation must support relational
  operators >, <, and == to allow comparison of

slide 602

Shared By: