Вы находитесь на странице: 1из 84

Programming

• Computer program - a sequence of statements designed to accomplish some


task
• Programming - a process of planning and creating a program
• Syntax - rules that tell us which statements (instructions) are legal
• Programming language - a set of rules, symbols, and special words
• Semantic rules - determine the meaning of the instructions
• Metalanguage - language used to write the syntax rules

C++ Programs
• A C++ program is a collection of one or more subprograms, called functions
• A subprogram or a function is a collection of statements that when activated
(executed) accomplishes something
• Every C++ program has a function called main
• The smallest individual unit of a program written in any language is called a
token

Symbols
• Special symbols include:
• +
• -
• *
• /
• .
• ;
• ?
• ,
• <=
• !=
• ==
• >=

Symbols
• Word symbols
• are called reserved words, or keywords
• include: int, float, double, char, void, return

Identifiers
• Consist of letters, digits, and the underscore character (_)
• Must begin with a letter or underscore
C++ is case sensitive—uppercase and lower case letters are different
Start here Page 1
• C++ is case sensitive—uppercase and lower case letters are different
• Some of the predefined identifiers are cout and cin
• Unlike reserved words, predefined identifiers may be redefined, but it would
not be wise to do so

Legal and Illegal Identifiers


• The following are legal identifiers in C++:
• first
• conversion
• payRate

Simple Data Types


• Data Type - a set of values together with a set of operations is called a data
type
• C++ simple data can be classified into three categories
• integral - deals with integers, or numbers without a decimal part
• floating-point - deals with decimal numbers
• enumeration type - user-defined data type

Values and Memory Allocation

int Data Type


• Examples:
• -6728
• 0
• 78
• Positive integers do not have to have a + sign in front of them
• No commas are used within an integer
• In C++, commas are reserved for separating items in a list

bool Data Type


The data type bool has two values, true and false The central purpose of

Start here Page 2


• The data type bool has two values, true and false The central purpose of
this data type is to manipulate logical (Boolean) expressions True and false
are called logical (Boolean) values In C++ bool, true, and false are reserved
words

char Data Type


• The smallest integral data type
• Used to represent characters, that is letters, digits, and special symbols
• Each character is enclosed within single quote marks
• Some of the values belonging to char data type are:
• 'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a character and is written ' ', with a space left between the
single quotes

• To represent real numbers C++ uses scientific notation called floating-point


notation
Floating-Point Data Types

Floating-Point Data Types


• Float - used in C++ to represent any real number between -3.4E+38 and
3.4E+38 The memory allocated for the float data type is 4 bytes Double -
used in C++ to represent any real number between -1.7E+308 and 1.7E+308
The memory allocated for the double data type is 8 bytes On most newer
compilers, the data types double and long double are the same

Floating-Point Data Types


• The maximum number of significant digits (decimal places) in float values is 6
or 7
• Float values are called single precision
• The maximum number of significant digits in values belonging to the double
type is 15
• Double values are called double precision
• The maximum number of significant digits is called the precision

string Data Type


• Programmer-defined type supplied in the standard library
• Sequence of zero or more characters
• Enclosed in double quotation marks
A string with no characters is called a null or empty string
Start here Page 3
• A string with no characters is called a null or empty string
• Every character has a relative position in the string
• The position of the first character is 0, the position of the second character is
1, and so on
• Length of a string is the number of characters in it

Arithmetic Operators
• C++ Operators
• + addition
• - subtraction
• * multiplication
• / division
• % remainder (mod operator)
• The operators +, -, *, and / can be used with both integral and floating-point
data types
• The % is used only with the integral data type to find the remainder in
ordinary division
• Unary operator - has only one operand
• Binary Operator - has two operands

Order of Precedence
• All operations inside of ( ) are evaluated first
• The operators *, /, and % are at the same level of precedence and are
evaluated next The operators + and – have the same level of precedence
and are evaluated last When operators are all on the same level, they are
performed from left to right

Mixed Expressions
• Mixed expression - an expression that has operands of different data types
• Contains both integers and floating-point numbers
• Examples of mixed expressions:
• 2 + 3.5
• 6 / 4 + 3.9
• 5.4 * 2 – 13.6 + 18 / 2

Evaluating Mixed Expressions


• If the operator has the same types of operands, it is evaluated according to
the type of the operands
• If the operator has both types of operands,
• during calculation the integer is changed to a floating-point number with the
decimal part of zero and the operator is evaluated
• the result is a floating-point number

Evaluating Mixed Expressions


• The entire expression is evaluated according to the precedence rules
• the multiplication, division, and modulus operators are evaluated before the
addition and subtraction operators
operators having the same level of precedence are evaluated from left to right
Start here Page 4
• operators having the same level of precedence are evaluated from left to right
• grouping is allowed for clarity

Assignment Statement
• The assignment statement takes the form:
variable = expression;
• The expression is evaluated and its value is assigned to the variable on the
left side
• In C++ = is called the assignment operator
• A C++ statement like:
I = I + 2;
• Evaluates whatever is in I, adds two to it, and assigns the new value to the
memory location I

Declaring & Initializing Variables


• Variables can be initialized when they are declared
• For example:
int first=13, second=10;
char ch=' ';
double x=12.6, y=123.456;
• This will declare first and second as integer and fill them with the values 13
and 10 respectively

Allocating Memory
• Named Constant - memory location whose content is not allowed to change
during program execution Variable - a memory location whose content may
change during program execution
• The syntax to declare a named constant is:
const dataType identifier = value;
• In C++, const is a reserved word

Input (Read) Statement


• Syntax of cin together with >> is used to gather input
cin>>variable>>variable. . .;
• The extraction operator is >>
• For example, if miles is a variable of the type double the statement:
cin>>miles;
• It causes the computer to get a value of the type double and place it in the
memory cell miles

Input Statement
• Using more than one variable in cin allows more than one value to be read at
a time For example, if feet and inch are variables of the type int a statement
like:
cin>>feet>>inch;
• Inputs two integers that are entered at the keyboard and places them in the
memory location feet and inch, respectively

Start here Page 5


Increment & Decrement Operators
• Increment operator - increments the value of a variable by 1 Decrement
operator - decrements the value of a variable by 1
• Pre-increment: ++variable
• Post-increment: variable++
• Pre-decrement: --variable
• Post-decrement: variable--

Increment & Decrement Operators


For example:
• ++count; or count++; increments the value of count by 1
• --count; or count--; decrements the value of count by
• If you have x = 5; and y = ++x;
• after the second statement both x and y are 6.
• If you have x = 5; and y = x++;
• after the second statement y is 5 and x is 6.

Output
• The syntax of cout together with << is:
cout<<expression or manipulator<<expression or manipulator...;
• This is called an output statement
• The << operator is called the insertion operator or the stream insertion
operator
• Sometimes this is also called a cout statement

Output
• In the example:
cout<<expression or manipulator<<expression or manipulator...;
• expression is evaluated and its value is printed at the current cursor position
on the screen
• manipulator - manipulates the output
• endl - the simplest manipulator which causes the cursor to move to the
beginning of the next line

Output Example
• The output of the C++ statement cout<<a; is meaningful provided the
variable a has been given a value
• For example, the sequence of C++ statements,
a = 45;
cout<<a;
will produce an output of 45

Program Example
int a, b, c, d;
a = 65 ; //Line 1
b = 78 ; //Line 2
cout<<29/4<<endl; //Line 3

Start here Page 6


cout<<29/4<<endl; //Line 3
cout<<3.0/2<<endl; //Line 4
cout<<"Hello there.\n"; //Line 5
cout<<7<<endl; //Line 6
cout<<3+5<<endl; //Line 7
cout<<"3+5"; //Line 8
cout<<endl; //Line 9

Output of Statement
• 7 at Line 3
• 1.5 at Line 4
• Hello there. at Line 5
• 7 at Line 6
• 8 at Line 7
• 3+5 at Line 8

The New Line Character


• The new line character is ―\n‖
• Without this character the output is printed on one line
• This command tells the output to go to the next line
• When \n is encountered in the string, the cursor is positioned at the beginning
of the next line
• A \n may appear anywhere in the string

Examples
• Without the new line character:
cout<<"Hello there.";
cout<<"My name is Goofy.";
• Would output:
Hello there.My name is Goofy.
• With the new line character:
cout<<"Hello there.\n";
cout<<"My name is Goofy.";
• Would output
Hello there.
My name is Goofy.

Common Escape Sequences

Start here Page 7


Common Escape Sequences

Preprocessor Directives
• Only a small number of operations are explicitly defined in C++
• Many of the functions and symbols that are necessary to run a C++ program
are provided as a collection of libraries
• Every library has a name and is referred to by a header file
• Preprocessor directives are commands supplied to the preprocessor
• All preprocessor commands begin with #
• There is no semicolon at the end of these commands

Preprocessor Directive Syntax


• The general syntax to include a header file (provided by the SDK) in a C++
program is:
#include <headerFileName>
• The preprocessor directive causes the preprocessor to include the header file
iostream in the program
• The syntax is:
#include <iostream>

Header Files
• In Standard C++, header files have the file extension .h
• The descriptions of the functions needed to perform I/O are contained in the
header file iostream.h
• The syntax is:
• #include <iostream.h>
• #include <math.h>

Start here Page 8


Processing a C++ Program

Program Style and Form


• The program part
• every C++ program has a function main
• the basic parts of the function main are:
• the heading
• the body of the function
• The heading part has the following form
typeOfFunction main(argument list)

Body and Syntax


• The body of the function is enclosed between { and }
• It has two types of statements
• declaration statements
• executable statements
• Syntax
• Errors in syntax are detected during compilation.
int x; //Line 1
int y //Line 2: syntax error
double z; //Line 3
y = w + x; //Line 4: syntax error

Statements
• Declaration Statements
int a, b, c;
double x, y;
• Variables can be declared anywhere in the program, but they must be
declared before they can be used
Executable Statements have three forms:
Start here Page 9
• Executable Statements have three forms:
a = 4; //assignment statement
cin>>b; //input statement
cout<<a<<endl<<b<<endl; //output statement

Special Characters
• Use of Blanks
• one or more blanks are used to separate numbers when data is input
• blanks are also used to separate reserved words and identifiers from each
other and other symbols
• The blanks between the identifiers in the second statement are meaningless:
• int a,b,c;
• int a, b, c;
• In the statement: inta,b,c;
no blank between the t and a changes the reserved word int and the
identifier a into a new identifier, inta

Semicolons, Brackets, & Commas


• Commas are used to separate items in a list
• All C++ statements terminate with a semicolon The semicolon is also called
a statement terminator
• { and } are not C++ statements

Semantics
• It is possible to eradicate all syntax errors in a program and still not have it
run
• It is also possible that if it runs it still may not do what you meant it to do
• For example,
2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions, but have different meanings

Form and Style


• Consider the following two ways of declaring variables:
• Method 1
int feet, inch;
double x, y;
• Method 2
int a,b;double x,y;
• Both are correct, however, the second declares all of the variables on one line

Documentation
• Comments can be used to document the code
• Single line comments begin with // anywhere in the line
• Multiple line comments are enclosed between /* and */
• Name identifiers with meaningful names
• Run-together-words can be handled either by using capitals for the beginning
of each new word or an underscore just before the new word

Start here Page 10


Body of the Function
• The body of the function main has the following form:
int main ()
{
declare variables
statements
return 0;
}

Writing a Complete Program


• Begin the program with comments for documentation Include header files, if
any are used in the program
• Declare named constants, if any
• Write the definition of the func

Input/Output Streams
• I/O - sequence of bytes (stream of bytes) from source to destination
• The bytes are usually characters, unless the program requires other types of
information
• Stream - sequence of characters from source to destination
• Input Stream - sequence of characters from an input device to the computer
• Output Stream - sequence of characters from the computer to an output
device

Standard I/O Devices


• To extract (receive) data from a keyboard and send output to the screen use
the header file iostream
• The header file iostream contains definitions of two data types
• istream - input stream
• ostream - output stream
• The header file iostream contains the declaration of two variables
• cin - stands for common input
• cout - stands for common output

Using cin and cout


• To use cin and cout, the preprocessor directive #include <iostream> must
be used
• The declaration is similar to the following C++ statements:
• istream cin;
• ostream cout;
• Input stream variables - variables of type istream
• Output stream variables - variables of type ostream
• Stream variable - either input or output stream variable

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

Start here Page 11


Standard Input
• The syntax of an input statement using cin and the extraction operator >> is
cin>>variable>>variable...;
• The extraction operator >> is binary
• The left-hand operand is an input stream variable such as cin The right-
hand operand is a variable of a simple data type
Standard Input
• Every occurrence of >> extracts the next data item from the input stream
• Two variables can be read using a single cin statement
• There is no difference between a single cin with multiple variables and
multiple cin statements with one variable
• When scanning, >> skips all whitespaces
• Whitespace characters consist of blanks and certain nonprintable characters

Data Type of Input


• >> distinguishes between character 2 and the number 2 by the right hand
operand of >>
• If it is of type char, the 2 is treated as character 2
• If it is of the type int (or double) the 2 is treated as the number 2

Reading Data
• When reading data into a char variable, after skipping any leading whitespace
characters, the extraction operator >> finds and stores only the next
character
• reading stops after a single character
• To read data into an int or double variable, after skipping all leading
whitespace characters and reading the plus or minus sign (if any), the
extraction operator >> reads the digits of the number, including the decimal
point for floating-point variables
• reading stops when it finds a whitespace character or a character other than a
digit
Using Predefined Functions
• A function, also called a subprogram, is a set of instructions
• When a function is activated (executed) it accomplishes something
• The function main is executed automatically when a program is executed
• Other functions are executed only when they are called
• C++ comes with a wealth of functions
• Predefined functions are organized as a collection of libraries called header
files
Predefined Functions

Start here Page 12


Predefined Functions
• A particular header file may contain several functions
• To use a predefined function you need the name of the header file containing
the specification of the function
• You also need to know:
• the name of the function
• the number of parameters the function takes
• the type of each parameter
• what the function is going to do
Predefined Function Example
• To use the function pow, you must include the header file cmath
• It has two parameters which are numbers
• It calculates the first parameter to the power of the second parameter
• The syntax is: pow(x,y) = xy
• x and y are the arguments or parameters
• In pow(2,3), the parameters are 2 and 3
• Expressions like pow(2,3) are called function calls

The get Function


• The get function
• inputs the very next character (including whitespaces) from the input stream
• stores the character in the memory location indicated by its argument
• The syntax of cin and the get function to read a character is:
cin.get(varChar);
• varChar is a char variable
• It is the argument (parameter) of the function
• The next input character is stored in varChar
The ignore Function
• The ignore function can be used to discard some portion of the input
• The syntax to use the function ignore is:
cin.ignore(intExp,chExp);
• intExp is an integer expression yielding an integer value
• chExp is a char expression
• For example, if intExp is a value m the above statement says ignore the next
m characters or all characters until the character specified by chExp,
whichever comes first
The peek & putback Functions
• The putback function
• places the previous character extracted by the get function from an input
stream back to that stream
• The peek function
• returns the next character from the input stream
• does not remove the character from that stream
The peek & putback Syntax
• The syntax to use the function putback is:
• istreamVar.putback(ch);
istreamVar - an input stream variable, such as cin

Start here Page 13


• istreamVar - an input stream variable, such as cin
• ch is a char variable
• The syntax to use the function peek is:
• ch = istreamVar.peek();
• istreamVar is an input stream variable, such as cin,
• ch is a char variable
Input Failure
• Many things can go wrong during program execution
• A program that is syntactically correct might produce incorrect results
• If the input data did not match the corresponding variables, the program
would run into problems
• Trying to read a letter into an int or double variable would result in an input
failure
• The clear function can be used to restore the input stream to a working state
Input Failure
• When an error occurs when a program is reading data, the input stream
enters the fail state
• Once an input stream enters a fail state, all further I/O statements using that
stream are ignored
• Unfortunately, the program continues to execute with whatever values are
stored in variables
• This results in incorrect results

Writing to Standard Output


• Syntax of cout when used together with the insertion operator << is:
cout<<expression or manipulator
<<expression or manipulator...;
• First expression is evaluated
• Next, its value is printed
• manipulator is used to format the output
Formatting Output
• endl is used to move the output to the beginning of the next line
• setprecision(n) will output decimal numbers with up to n decimal places
• fixed will output floating-point numbers in a fixed decimal format
• showpoint is used to force the output to show the decimal point and trailing
zeros
• The stream function setf can be used to set fixed, scientific, and showpoint
Formatting Output
• The manipulator setiosflags
• is used to set the flags ios::fixed, ios::scientific, and ios::showpoint
• to use the manipulator setiosflags, the program must include the header file
iomanip
• to specify more than one flag in the manipulator setiosflags, separate the
flags with the symbol |
• setw(n)
• output the value of the next expression in n columns
the output is right justified

Start here Page 14


• the output is right justified
Additional Output Tools
• fill and setfill
• In the manipulator setw if the number of columns specified are more than the
number of columns required by the expression the output of the expression is
right-justified and the unused columns to the left are filled with spaces
• The output stream variables, such as cout, can use the function fill and/or the
manipulator setfill to fill the unused columns with a character other than the
space
left & right Manipulators
• The manipulator left is used to left-justify the output The syntax to set the
manipulator left is ostreamVar<<left; The manipulator right is used to right-
justify the output The syntax to set the manipulator right is
ostreamVar<<right;
The flush Function
• The function flush clears the buffer, even if it is not full
• Unlike endl it does not move the cursor to the beginning of the next line
• The syntax to use the flush function is:
ostreamVar.flush();
• ostreamVar is an output stream variable
• It can be used as a manipulator
• in this case flush is used in an output statement without the parentheses
• for example: cout<<flush;
Types of Manipulators
• There are two types of manipulators:
• those with parameters
• those without parameters
• Parameterized stream manipulators - manipulators with parameters such as
setprecision, setw, setfill, and setiosflags require the iomanip header file
• Manipulators such as endl, fixed, scientific, showpoint, left, and flush are
without parameters and are part of the iostream header file

I/O With the string Type


• An input stream variable such as cin can be used with the extraction
operator >> to read a string into a variable of the data type string
• The extraction operator
• skips any leading whitespace characters and reading stops at a whitespace
character
• should not be used to read strings that contain blanks
• The function getline
• reads until it reaches the end of the current line
• should be used to read strings that contain blanks

File Input/Output
• File - an area in secondary storage used to hold information
• For file I/O, the following steps are necessary
1.Include the header file fstream in the program requiring the

Start here Page 15


1.Include the header file fstream in the program requiring the
following statement: #include <fstream>
2.Declare file (fstream) variables and declare the variable inData for
the input (file) stream and outData for the output (file) stream
3.Open Files using syntax such as
fileStreamVariable.open(sourceName, fileOpeningMode);

File Input/Output
4.Use the (file) stream variable together with >>, <<, or other
functions for input/output
•The syntax for using >> or << with file variables is exactly
the same as the syntax of cin and cout
5.The syntax for using >> or << with file variables is exactly similar
to the syntax of cin and cout
Finally, close files using:
•inData.close();
•outData.close();

Chapter 4
CONTROL STRUCTURES I
(Selection)

Control Structures
• A computer can proceed:
• in sequence
• selectively (branch) - making a choice
• repetitively (iteratively) - performing a statement over and over, also called a
loop
• Some statements are executed only if certain conditions are met
• A condition is represented by a logical (Boolean) expression that has a value
of either true or false
• A condition is met if it evaluates to true

Start here Page 16


Relational Operators
• A relational operator allows you to make comparisons in a program
• Equality of real numbers is usually machine dependent so it is possible that on
a particular machine 6.8 + 3.1 == 2.7 + 7.2 might evaluate to false
• Comparing values of different data types may produce unpredictable results
• For example, 8 < '5' should not be done
• C++ returns an integer value of 1 if the logical expression evaluates to true
and the value of 0 otherwise
• In C++, any nonzero value is treated as true

Relational Operators in C++

Start here Page 17


Comparing string Types
• Relational operators can be applied to string variables
• They are compared character by character, starting with the first character,
using the collating sequence
• This comparison continues until either a mismatch is found or the last
characters have been compared and are equal
• If two strings of different lengths are compared and the comparison is equal
to the last character of the shorter string, the shorter string is less than the
larger string

Logical (Boolean) Operators


• Logical (Boolean) operators enable you to combine logical expressions
• There are three logical (Boolean) operators:
• ! - not
• && – and
• || - or
• Logical operators take logical values as operands and yield logical values as
results
• ! is unary, so it has only one operand, while && and || are binary operators
• Putting ! in front of a logical expression reverses the value of that logical
expression

Precedence of Operators
• Relational and logical operators are evaluated from left to right so the
associativity is said to be from left to right
• Parentheses can be used to indicate an order of operation that is different
than the order indicated by order of precedence
• Short-circuit evaluation (of a logical expression) - a process in which the
computer evaluates a logical expression from left to right and stops as soon
as the value of the expression is known

Start here Page 18


Logical (Boolean) Assignments
• The int Data Type and Logical (Boolean) Expressions
• earlier versions of C++ had no built in data type that had logical (or Boolean)
values, true and false
• since logical expressions are evaluated to either 1 or 0, the value of a logical
expression is stored in a variable of the type int
• logical (Boolean) expressions were manipulated with the help of the int data
type
• any nonzero value is treated as true

Logical (Boolean) Assignments


• The bool Data Type and Logical (Boolean) Expressions
• recent versions of C++ contain a built in data type called bool
• the data type bool has logical (Boolean) values true and false
• in C++, bool, true, and false are reserved words
• the identifier true has the value 1
• the identifier false has the value 0

Logical (Boolean) Assignments


• Logical expressions do not always behave as expected
• The following expression appears to represent a comparison of 0, num, and
10:
0 <= num <= 10
• It will always evaluate to true because 0 <= num evaluates to either 0 or 1,
and 0 <= 10 is true and 1 <= 10 is true
• The correct way to write this expression is:
0 <= num && num <= 10

One-Way (if) Selection


• The syntax of one-way selection is:
if(expression)
statement
• If the value of the expression is true the statement is executed
• If the value is false the statement is not executed and the computer goes on
to the next statement in the program

Start here Page 19


• The expression is usually a logical expression
• statement is any C++ statement
• if is a reserved word

One-Way Selection

Two-Way (if…else) Selection


• Two-way selection takes the form:
if(expression)
statement1
else
statement2
• If the value of the expression is true, statement1 is executed otherwise
statement2 is executed
• statement1 and statement2 are any C++ statements
• else is a reserved word

Start here Page 20


Compound Statement
• A compound statement (also called a block of statements) takes the form
{
statement1;
statement2;
.
.
.
statementn;
}
• A compound statement is considered a single statement

Compound Statement Example


if(age > 18)
{
cout<<" Eligible to vote."<<endl;
cout<<" No longer a minor."<<endl;
}
else
{
cout<<"Not eligible to vote."<<endl;
cout<<"Still a minor."<<endl;
}

Nested if
• When one control statement is within another, it is said to be nested
• An else is associated with the most recent if that has not been paired with an
else
For example:
Start here Page 21
• For example:
if(score >= 90)
cout<<"The grade is A"<<endl;
else if(score >= 80)
cout<<"The grade is B"<<endl;
else
cout<<"The grade is F"<<endl;

switch Structures
• In a switch structure, the expression is evaluated first
• Next, the value of the expression is used to perform the corresponding action
• The expression is usually an identifier
• It is sometimes called the selector
• The expression value can be only integral
• Its value determines which statement is selected for execution
• A particular case value should appear only once

switch Structures
• One or more statements may follow a case label
• Braces are not needed to turn multiple statements into a single compound
statement
• The break statement may or may not appear after each statement
• The break statement has a special meaning and may or may not appear after
each statement
• switch, case, break, and default are reserved words

switch Statement Rules


• When the value of the expression is matched against a case value, the
statements execute until a break statement is found or the end of the switch
structure is reached
• If the value of the expression does not match any of the case values, the
statements following the default label execute. If there is no default label, and
if the value of the expression does not match any of the case values, the
entire switch statement is skipped
• A break statement causes an immediate exit from the switch structure

The assert Function


• Certain types of errors that are very difficult to catch can occur in a program
For example, division by zero can be difficult to catch using any of the
programming techniques we have examined so far The predefined
function, assert, is useful in stopping program execution when certain elusive
errors occur

The assert Function


• Certain types of errors that are very difficult to catch can occur in a program
For example, division by zero can be difficult to catch using any of the
programming techniques we have examined so far The predefined
function, assert, is useful in stopping program execution when certain elusive
Start here Page 22
function, assert, is useful in stopping program execution when certain elusive
errors occur

The assert Function


• The syntax to use the assert function is:
assert(expression);
• expression is any logical expression
• If expression evaluates to true, the next statement executes
• If the expression evaluates to false, the program terminates and indicates
where in the program the error occurred
• The specification of the assert function is found in the header file cassert
The assert Function
• The assert statement is very useful for enforcing programming constraints
during program development
• After a program has been developed and put into use, if an assert statement
fails for some reason, an end user would have no idea what the error means
• After developing and testing a program, remove or disable assert statements
• The preprocessor directive #define NDEBUG must be placed before the
directive #include <cassert> to disable the assert statement

Chapter 5
CONTROL STRUCTURES II
(Repetition)

Why Use Repetition?


• Repetition allows you to efficiently use variables
• Can input, add, and average multiple numbers using a limited number of
variables
• For example, you can add five numbers together by:
• declaring a variable for each number, inputting the numbers and adding the
variables together
• creating a loop that reads a number into a variable and adds it to a variable
that contains the sum of the numbers and looping until all numbers are read

The while Loop


• The general form of the while statement is:
while(expression)
statement
• while is a reserved word
• The statement can be simple or compound
• The expression acts as a decision maker and is usually a logical expression
• The statement is called the body of the loop
• The parentheses are part of the syntax

The while Loop


The expression provides an entry condition

Start here Page 23


• The expression provides an entry condition
• The statement executes if the expression initially evaluates to true
• The loop condition is then reevaluated
• If it is still true, the statement executes again
• The statement continues to execute until the expression is no longer true
• An infinite loop continues to execute endlessly and can be avoided by making
sure that the loop’s body contains statement(s) that assure that the exit
condition will eventually be false

Sentinel-Controlled while Loops


• A sentinel variable is tested in the condition and the loop ends when the
sentinel value is encountered
• The syntax is:
cin>>variable;
while(variable != sentinel)
{
.
cin>> variable;
.
}

Flag-Controlled while Loops


• A flag-controlled while loop uses a Boolean variable to control the loop
• The flag-controlled while loop takes the form:
found = false;

Start here Page 24


while(!found)
{
.
if(expression)
found = true;
.
}

EOF-Controlled while Loops


• An input stream variable, such as cin, returns a value, after reading data, as
follows:
• If the program has reached the end of input data, the input stream variable
returns the logical value false
• If the program reads a faulty data the input stream enters into the fail state
which means that any further I/O operations using that stream are considered
to be null operations and cin returns the value false
• In cases other than the above, it returns the logical value true
• The logical value returned by cin can determine if the program has ended
input

The eof Function


• The function eof with an input stream variable can also be used to determine
the end of file status
• Like the I/O functions, such as get, ignore, and peek, the function eof is also
a member of data type istream
• The syntax to use the function eof is:
istreamVar.eof()
where istreamVar is an input stream variable, such as cin

The for Loop


• The general form of the for statement is:
for(initial statement; loop condition;
update statement)
statement
• The initial statement, loop condition, and update statement (called for loop
control statements) that are enclosed within the parentheses control the body
of the for statement

Start here Page 25


The for Loop
• The for loop executes as follows:
• The initial statement executes
• The loop condition is evaluated
• if the loop condition evaluates to true
• execute the for loop statement
• execute the update statement (the third expression in the parentheses)
• Repeat the previous step until the loop condition evaluates to false
• The initial statement initializes a variable
• The initial statement in the for loop is the first to be executed and is executed
only once

The for Loop


• If the loop condition is initially false, the loop body does not execute The
update expression, when executed, changes the value of the loop control
variable which eventually sets the value of the loop condition to false The
for loop executes indefinitely if the loop condition is always true

The for Loop


• Fractional values
• can be used for loop control variables of the double type or any real data type
• should be avoided because different computers can give different results for
the variables
• A semicolon at the end of the for statement (just before the body of the loop)
is a semantic error, in this case, the action of the for loop is empty
• If the loop condition is omitted it is assumed to be true

The for Loop


• In a for statement, all three statements—initial statement, loop condition, and

Start here Page 26



update statement can be omitted
• The following is a legal for loop:
for(;;)
cout<<"Hello"<<endl;

The do…while Loop


• The general form of a do...while statement is:
do
statement
while(expression);
• The statement executes first, and then the expression is evaluated
• If the expression evaluates to true, the statement executes again
• As long as the expression in a do...while statement is true, the statement
executes

The do…while Loop


• To avoid an infinite loop, the loop body must contain a statement that
ultimately makes the expression false and assures that it exits
• The statement can be a simple or a compound statement
• If it is a compound statement, it must be enclosed between braces
• Because the while and for loop has an entry condition, it may never activate,
whereas, the do...while loop, which has an exit condition, always goes
through at least once

Break & Continue Statements


• A break and continue statement alters the flow of control
• The break statement, when executed in a switch structure, provides an
immediate exit from the switch structure
The break statement can be used in while, for, and do...while loops

Start here Page 27


• The break statement can be used in while, for, and do...while loops
• When the break statement executes in a repetition structure, it immediately
exits from these structures

Break & Continue Statements


• The break statement is typically used for two purposes:
• 1. To exit early from a loop
• 2. To skip the remainder of the switch structure
• After the break statement executes, the program continues to execute with
the first statement after the structure
• The use of a break statement in a loop can eliminate the use of certain (flag)
variables

Break & Continue Statements


• The continue statement is used in while, for, and do-while structures
• When it is executed in a loop, it skips the remaining statements and proceeds
with the next iteration of the loop
• In a while and do-while structure, the expression (loop-continue test) is
evaluated immediately after the continue statement
• In a for structure, the update statement is executed after the continue
statement, and then the loop condition executes

Nested Control Structures


• Suppose we want to create the following pattern
*
**
***
****
*****
• In the first line we want to print one star, in the second line two stars and so
on

Nested Control Structures


• Since five lines are to be printed, we start with the following for statement
for(i = 1; i <= 5 ; i++)
• The value of i in the first iteration is 1, in the second iteration it is 2, and so
on
• We can use the value of i as the limiting condition in another for loop nested
within this loop to control the number of starts in a line

Nested Control Structures


• The syntax would be:
for(i = 1; i <= 5 ; i++)
{
for(j = 1; j <= i; j++)
cout<<"*";
cout<<endl;
}
Start here Page 28
}

Nested Control Structures


• What pattern does the code produce if we replace the first for statement with
the following?
for(i = 5; i >= 1; i--)
• Answer:
*****
****
***
**
*

Chapter 6
USER-DEFINED FUNCTIONS I

Functions
• Functions are like building blocks
• They allow complicated programs to be divided into manageable pieces
• Some of the advantages of functions are:
• A programmer can focus on just that part of the program and construct it,
debug it, and perfect it
• Different people can work on different functions simultaneously
• If a function is needed in more than one place in a program, or in different
programs, you can write it once and use it many times

Functions
• are often referred to as modules
• are like miniature programs
• can be put together to form a larger program

Standard Functions
• In college algebra a function is defined as a rule or correspondence between
values, called the function’s arguments, and the unique value of the function
associated with the arguments
• If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11
• 1, 2, and 3 are arguments
• 7, 9, and 11 are the corresponding values

Standard Functions
• Some of the predefined mathematical functions are:
• sqrt(x)
• pow(x,y)
• floor(x)
• Predefined functions are organized into separate libraries
• I/O functions are contained in the header file iostream
Math functions are contained in the header file cmath

Start here Page 29


• Math functions are contained in the header file cmath

The power Function (pow)


• pow(x,y) calculates xy, for example: pow(2,3) = 8.0 is of the type double or
the function pow returns a value of the type double x and y are called the
parameters (or arguments) of the function pow
• Function pow has two parameters

The sqrt and floor Functions


• The square root function sqrt(x)
• calculates the non-negative square root of x for x >= 0.0
• sqrt(2.25) is 1.5
• It is of the type double and has only one parameter
• The floor function floor(x)
• calculates the largest whole number not greater than x
• floor(48.79) is 48.0
• It is of the type double and has only one parameter

User-Defined Functions
• Void functions - functions that do not have a data type
• Value-returning functions - functions that have a data type
• To use these functions you need to:
• include the correct header file
• know the name of the function
• know the number of parameters, if any
• know the data type of each parameter
• know the data type of the value computed by the function, called the type of
the function

Start here Page 30


User-Defined Functions
• Since the value returned by a value-returning function is unique, we:
• save the value for further calculation
• use the value in some calculation
• print the value
• A value-returning function is either used in an assignment statement or in an
output statement such as cout
• There is one more thing that is associated with a function:
• the code that is required to accomplish the task

User-Defined Functions
• The first four properties form the heading of the function
• The fifth property is called the body of the function
• These properties form the function definition
• For predefined functions, we only need to be concerned with the first four
properties
• Formal Parameter - A variable declared in the function heading
• Actual Parameter - A variable or expression listed in a call to a function

Value-returning Functions
• The syntax is:
functionType functionName(formal parameter list)
{
statements
}
• functionType - type of the value returned by the function
• functionType - also called the data type of the value-returning function

Syntax
• The syntax of the formal parameter list is:
dataType identifier, dataType identifier, ...
• The syntax for a function call is:
functionName(actual parameter list)
• The syntax for the actual parameter list is:
expression or variable,expression or variable, ...

Functions
• The formal parameter list can be empty
• If the formal parameter list is empty
• the parentheses are still needed
• the function heading of the value-returning function takes either of the
following forms:
• functionType functionName()
• functionType functionName(void)
• in a function call the actual parameter is empty
A call to a value-returning function with an empty formal parameter list is:

Start here Page 31


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

Value-Returning Functions
• To call a value-returning function:
• Use its name, with the actual parameters (if any) in parentheses
• There is a one-to-one correspondence between actual and formal parameters
• A value-returning function is called in an expression
• The expression may be part of an assignment statement or an output
statement
• A function call in a program results in the execution of the body of the called
function

The return Statement


• Once the function computes the value, the function returns this value via the
return statement
• The syntax of the return statement is:
return expression or variable;
• When a return statement executes in a function, the function immediately
terminates and the control goes back to the caller
• When a return statement executes in the function main, the program
terminates

Function Prototype
• Function Prototype - function heading without the body of the function
• The syntax is:
functionType functionName(parameter list);
• It is not necessary to specify the variable name in the parameter list The
data type of each parameter must be specified

Flow of Execution
• When the program is executed (run), execution always begins at the first
statement in the function main no matter where it is placed in the program
• Other functions are executed only when they are called
• Function prototypes appear before any function definition, so the compiler
translates these first
• The compiler can then correctly translate a function call

Flow of Execution
• A function call statement results in the transfer of control to the first
statement in the body of the called function
• After the last statement of the called function is executed, the control is
passed back to the point immediately following the function call
• A value-returning function returns a value
• After executing the function when the control goes back to the caller, the
value that the function returns replaces the function call statement

Chapter 7

Start here Page 32


Chapter 7
USER-DEFINED FUNCTIONS II

Void Functions
• Void functions and value-returning functions have similar structures
• Both have a heading part and a statement part
• User-defined void functions can be placed either before or after the function
main The program execution always begins with the first statement in the
function main If user-defined void functions are placed after the function
main, the function prototype must be placed before the function main

Void Functions
• Because a void function does not have a data type, putting functionType in
the heading part and the return statement in the body of the void function are
meaningless
• The return statement can be used without any value; it is typically used to
exit the function early
• May or may not have formal parameters
• A call to a void function is a stand-alone statement

Without Parameters
• Function definition syntax:
void functionName(void)
{
statements
}
• void inside the parentheses is optional
• void is a reserved word
• Function call syntax:
• functionName();

With Parameters
• Function definition syntax:
void functionName(dataType& variable, dataType& variable, …)
{
statements
}
• Value Parameter - a formal parameter that receives a copy of the content of
the corresponding actual parameter
• Reference Parameter - a formal parameter that receives the location (memory
address) of the corresponding actual parameter

Formal Parameters
• If a formal parameter is a value parameter, the value of the corresponding
actual parameter is copied into it The value parameter has its own copy of
the data During program execution, the value parameter manipulates the
data stored in its own memory space

Start here Page 33


Reference Parameter
• If a formal parameter is a reference parameter, it receives the address of the
corresponding actual parameter A reference parameter stores the address of
the corresponding actual parameter During program execution to
manipulate the data, the address stored in the reference parameter directs it
to the memory space of the corresponding actual parameter

Reference Parameter
• A reference parameter receives the address of the actual parameter
• They can pass one or more values from a function and can change the value
of the actual parameter
• Reference parameters are useful in three situations:
• Returning more than one value
• Changing the actual parameter
• When passing the address would save memory space and time

Parameters & Memory Allocation


• When a function is called, memory for its formal parameters and variables
declared in the body of the function (called local variables) is allocated in the
function data area
• In the case of a value parameter, the value of the actual parameter is copied
into the memory cell of its corresponding formal parameter
• In the case of a reference parameter, the address of the actual parameter
passes to the formal parameter

Parameters & Memory Allocation


• Content of the formal parameter is an address During execution, changes
made by the formal parameter permanently change the value of the actual
parameter Stream variables (for example, ifstream and ofstream) should be
passed by reference to a function

Scope of an Identifier
• The scope of an identifier refers to where in the program an identifier is
accessible (that is visible)
• Local identifier - identifiers declared within a function (or block)
• Global identifier – identifiers declared outside of every function definition
• C++ does not allow the nesting of functions, this means that the definition of
one function cannot be included in the body of another function

Scope of an Identifier
• Global identifiers (such as variables) are accessible by a function or a block if
• the identifier is declared before the function definition (block)
• the function name is different from the identifier
• all parameters of the function have names different than the name of the
identifier
• all local identifiers (such as local variables) have names different than the
name of the identifier

Start here Page 34



name of the identifier

Scope of an Identifier
• An identifier declared within a block (Nested Block) is accessible
• only within the block from the point it is declared until the end of the block
and
• by those blocks that are nested within that block if the nested block does not
have an identifier with the same name as that of the outside block (the block
that encloses the nested block)
• The scope of a function name is similar to the scope of an identifier declared
outside of any block

Global Variables
• Some compilers initialize global variables to default values
• The operator :: is called the scope resolution operator
• By using the scope resolution operator, a global variable declared before the
definition of a function (block) can be accessed by the function (or block)
even if the function (or block) has an identifier with the same name as the
variable

Global Variables
• C++ provides a way to access a global variable declared after the definition of
a function In this case, the function must not contain any identifier with the
same name as the global variable

Global Variable Side Effects


• Using global variables has side effects
• Any function that uses global variables is not independent and usually it
cannot be used in more than one program

Start here Page 35



cannot be used in more than one program
• If more than one function uses the same global variable and something goes
wrong, it is difficult to find what went wrong and where
• Problems caused by global variables in one area of a program might be
misunderstood as problems caused in another area

Static and Automatic Variables


• Automatic variable - a variable for which memory is allocated at block entry
and deallocated at block exit
• Static variable - a variable for which memory remains allocated as long as the
program executes
• Variables declared outside of any block are static variables
• By default variables declared within a block are automatic variables
• We can declare a static variable within a block by using the reserved word
static

Static and Automatic Variables


• The syntax for declaring a static variable is:
static dataType identifier;
• The statement
static int x;
declares x to be a static variable of the type int
• Static variables declared within a block are local to the block
• Their scope is the same as any other local identifier of that block

Function Overloading
• You can have several functions with the same name
• Every function must have a different set of parameters
• This is overloading a function name
• The types of parameters determine which function to be executed
• It is used when we have the same action for different sets of data
• For it to work, the definition of each of the functions must be given

Default Parameters
• When a function is called, the number of actual and formal parameters must
be the same C++ relaxes this condition for functions with default
parameters You specify the value of a default parameter when the function
name appears for the first time, such as in the prototype

Default Parameters
• If you do not specify the value of a default parameter, the default value is
used All the default parameters must be the rightmost parameters of the
function In a function call where the function has more than one default
parameter and a value to a default parameter is not specified, then you must
omit all of the arguments to its right

Default Parameters
Default values can be constants, global variables, or function calls The caller

Start here Page 36


• Default values can be constants, global variables, or function calls The caller
has the option of specifying a value other than the default for any default
parameter You cannot assign a constant value as a default value to a
reference parameter

Chapter 8
USER-DEFINED SIMPLE DATA
TYPES, NAMESPACES,
AND THE string TYPE

Enumeration Type
• Data type - a set of values together with a set of operations on those values
• To define a new simple data type, called enumeration type, we need three
things:
• a name for the data type
• a set of values for the data type
• a set of operations on the values
• A new simple data type can be defined by specifying its name and the values,
but not the operations
• The values must be identifiers

Enumeration Type
• The syntax for enumeration type is:
enum typeName{value1, value2, ...};
• value1, value2, … are identifiers
• They called enumerators
• value1 < value2 < value3 <...
• Enumeration type is an ordered set of values
• If a value has been used in one enumeration type, it cannot be used by
another in the same block
• The same rules apply to enumeration types declared outside of any blocks

Examples
• The following are illegal enumeration types because none of the values is an
identifier:
enum grades{'A', 'B', 'C', 'D', 'F'};
enum places{1st, 2nd, 3rd, 4th};
• The following are legal enumeration types:
enum grades{A, B, C, D, F};
enum places{first, second, third, fourth};

Declaring Variables
• The syntax for declaring variables is:
dataType identifier, identifier,...;
• The following statement defines an enumeration type sports
enum sports{basketball, football, hockey,
baseball, soccer, volleyball};
The following statement declares variables of the type sports.
Start here Page 37
• The following statement declares variables of the type sports.
sports popularSport, mySport;

Assignment
• The statement:
popularSport = football;
stores the word football in the variable popularSport
• The statement:
mySport = popularSport;
copies the contents of the variable popularSport in the variable mySport

Operations
• No arithmetic operation is allowed on enumeration types
• The following statements are illegal;
mySport = popularSport + 2; //illegal
popularSport = football + soccer; //illegal
popularSport = popularSport * 2; // illegal
• The increment and decrement operations are not allowed on enumeration
types
• The following statements are illegal;
popularSport++; //illegal
popularSport--; //illegal

Operations
• Because an enumeration is an ordered set of values, we can use relational
operators with them
• The cast operator can be used to increment, decrement, and compare the
values which means that they can be used in loops
• Input and output
• are defined only for built-in data types such as int, char, double
• the enumeration type can be neither input nor output (directly)
• you can input and output enumeration indirectly

Functions
• Enumeration type can be passed as parameters to functions either by value or
by reference A function can return a value of the enumeration type

Anonymous Data Types


• Anonymous - a data type in which values are directly specified in the variable
declaration with no type name, for example:
enum {basketball, football, baseball} mysport;
• Creating an anonymous type has drawbacks
• We cannot pass an anonymous type as a parameter to a function
• A function cannot return a value of an anonymous type
• Values used in one can be used in another, but they are treated differently

The typedef Statement


You can create synonyms or aliases to a previously defined data type by using

Start here Page 38


• You can create synonyms or aliases to a previously defined data type by using
the typedef statement
• The general syntax of the typedef statement is:
typedef existingTypeName newTypeName;
• The typedef statement does not create any new data types
• It creates only an alias to an existing data type

ANSI/ISO Standard C++


• ANSI/ISO standard C++ officially approved in July 1998
• Most of the recent compilers are also compatible with ANSI/ISO standard
C++
• In previous chapters, we mainly dealt with standard C++ and briefly
introduced the features of ANSI/ISO standard C++
• For the most part the two standards are the same
• In this chapter, we discuss some of the features of ANSI/ISO standard C++
language that are not available in standard C++

Namespaces
• When a header file, such as iostream, is included in a program, the global
identifiers in the header file also become global identifiers in the program
• If a global identifier in a program has the same name as one of the global
identifiers in the header file, the compiler will generate a syntax error (such as
identifier redefined)
• The same problem can occur if a program uses third party libraries

Namespaces
• To overcome this problem, third party vendors begin their global identifiers
with a special symbol
• Since compiler vendors begin their global identifier with _ (underscore), to
avoid linking errors do not begin identifiers in your program with _
(underscore)
• ANSI/ISO standard C++ attempts to solve this problem of overlapping global
identifier names with the namespace mechanism

Syntax: namespace
• The syntax of the statement namespace is:
namespace namespace_name
{
members
}
where a member is usually a variable declaration, a named constant, a
function, or another namespace

Accessing a namespace Member


• The scope of a namespace member is local to the namespace
• There are usually two ways a namespace member can be accessed outside
the namespace
One way is to use the syntax:
Start here Page 39
• One way is to use the syntax:
namespace_name::identifier
• To access the member rate of the namespace globalType, the following
statement is required:
globalType::rate

Accessing a namespace Member


• To access the member printResult (which is a function), the following
statement is required:
globalType::printResult();
• The other way to access a namespace is to use the statement using
• To simplify the accessing of all namespace members:
• using namespace namespace_name;
• To simplify the accessing of a specific namespace member:
using namespace_name::identifier;

The using Statement


• After the using statement it is not necessary to precede the namespace_name
and the scope resolution operator before the namespace member If a
namespace member and a global identifier or a block identifier have the same
name, the namespace_name and scope resolution operator must precede the
namespace member

The string Type


• To use the data type string, the program must include the header file string
• The statement:
string name = "William Jacob";
declares name to be a string variable and also initializes name to "William
Jacob"
• The first character, 'W', in name is in position 0, the second character, 'i', is in
position 1, and so on

The string Type


• The variable name is capable of storing just about any size string
• Binary operator + (to allow the string concatenation operation), and the array
index (subscript) operator [], have been defined for the data type string
• For example, If str1 = "Sunny", the statement
str2 = str1 + " Day";
stores the string "Sunny Day" into str2

The length Function


• Returns the number of characters currently in the string
• The value returned is an unsigned integer
• The syntax to call the length function is:
strVar.length()
where strVar is variable of the type string
• It has no arguments
It returns an unsigned integer
Start here Page 40
• It returns an unsigned integer
• The value returned can be stored in an integer variable

The size Function


• The function size is same as the function length
• Both functions return the same value
• The syntax to call the function size is:
strVar.size()
where strVar is variable of the type string
• As in the case of the function length, the function size has no arguments

The find Function


• The find function searches a string to find the first occurrence of a particular
substring and returns an unsigned integer value of type string::size_type
giving the result of the search
• The syntax to call the function find is:
strVar.find(strExp)
where strVar is a string variable and strExp is a string expression
evaluating to a string
• The string expression, strExp, can also be a character

The find Function


• If the search is successful, the function find returns the position in strVar
where the match begins For the search to be successful the match must be
exact If the search is unsuccessful, the function returns the special value
string::npos (―not a position within the string‖)

The substr Function


• Returns a particular substring of a string
• The syntax to call the function substr is:
strVar.substr(expr1,expr2)
where expr1 and expr2 are expressions evaluating to unsigned integers
• The expression expr1 specifies a position within the string (starting position of
the substring)
• The expression expr2 specifies the length of the substring to be returned

The Function swap


• Is used to swap, or interchange, the contents of two string variables
• The syntax to use the function swap is
strVar1.swap(strVar2);
where strVar1 and strVar2 are string variables
• Suppose you have the following statements:
string str1 = "Warm";
string str2 = "Cold";
• After str1.swap(str2); executes, the value of str1 is "Cold" and the value of
str2 is "Warm"

Chapter 9

Start here Page 41


Chapter 9
ARRAYS AND STRINGS

Data Types
• A data type is called simple if variables of that type can store only one value
at a time A structured data type is one in which each data item is a
collection of other data items

Arrays
• Array - a collection of a fixed number of components wherein all of the
components are of the same data type One-dimensional array - an array in
which the components are arranged in a list form The general form of
declaring a one-dimensional array is:
dataType arrayName[intExp];
where intExp is any expression that evaluates to a positive integer

Declaring an array
• The statement int num[5]; declares an array num of 5 components of the
type int The components are num[0], num[1], num[2], num[3], and num[4]

Accessing Array Components


• The general form (syntax) of accessing an array component is:
arrayName[indexExp]
where indexExp, called index, is any expression whose value is a
nonnegative integer Index value specifies the position of the
component in the array The [] operator is called the array subscripting
operator
• The array index starts at 0

Processing One-Dimensional Arrays


• Some of the basic operations performed on a one-dimensional array are:
• initialize
• input data
• output data stored in an array
• find the largest and/or smallest element
• Each of these operations requires the ability to step through the elements of
the array

Start here Page 42


• Stepping-through the elements of an array is easily accomplished by a loop

Accessing Array Components


• Consider the declaration
int list[100]; //list is an array of the size 100
int i;
• This for loop steps-through each element of the array list starting at the first
element
for(i = 0; i < 100; i++) //Line 1
process list[i] //Line 2
• If processing list requires inputting data into list, the statement in Line 2 takes
the form of an input statement, such as the cin statement
for(i = 0; i < 100; i++) //Line 1
cin>>list[i];

Array Index Out of Bounds


• If we have the statements:
double num[10];
int i;
• The component num[i] is a valid index if i = 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9
• The index of an array is in bounds if the index >=0 and the index <=
arraySize-1
• If either the index < 0 or the index > arraySize-1, then we say that the index
is out of bounds
• There is no guard against indices that are out of bounds because C++ does
not check if the index value is with in range

Array Initialization
• Like any other simple variable, arrays can also be initialized while they are
being declared When initializing arrays while declaring them, it is not
necessary to specify the size of the array The size of the array is determined
by the number of initial values in the braces
• For example:
double sales[] = {12.25, 32.50, 16.90, 23, 45.68};

Partial Initialization
• The statement
int list[10] = {0};
declares list to be an array of 10 components and initializes all
components to zero
• The statement
int list[10] = {8, 5, 12};
declares list to be an array of 10 components, initializes list[0] to 8, list[1]
to 5, list[2] to 12 and all other components are initialized to 0

Partial Initialization
• The statement
int list[] = {5,6,3};
Start here Page 43
int list[] = {5,6,3};
declares list to be an array of 3 components and initializes list[0] to 5,
list[1] to 6, and list[2] to 3
• The statement
int list[25]= {4,7};
declares list to be an array of 25 components. The first two components
are initialized to 4 and 7, respectively and all other components are
initialized to zero

Restrictions on Array Processing


• If x and y are two arrays of the same type and size then the following
statement is illegal:
y = x; // illegal
• In order to copy one array into another array we must copy component-wise
• This can be accomplished by a loop like the following
for(j = 0; j < 25; j++)
y[j] = x[j];

Restrictions on Array Processing


• Comparison of arrays, reading data into an array and printing the contents of
an array must be done component-wise
cin>>x; //illegal
cout<<y; //illegal
• C++ does not allow aggregate operations on an array
• An aggregate operation on an array is any operation that manipulates the
entire array as a single unit

Arrays as Parameters to Functions


• Arrays are passed by reference only
• The symbol & is used when declaring an array as a formal parameter
• The size of the array is usually omitted
• If the size of the one-dimensional array is specified when it is declared as a
formal parameter, it is ignored by the compiler The reserved word const in
the declaration of the formal parameter can still prevent the function from
changing the actual parameter

Base Address of an Array


• The base address of an array is the address, or memory location of the first
array component If list is a one-dimensional array, then the base address of
list is the address of the component list[0] When we pass an array as a
parameter, the base address of the actual array is passed to the formal
parameter
• The function can not return a value of the type array

C Strings (Character Arrays)


• Character array - an array whose components are of the type char is called a
character array
ch = '\0';
Start here Page 44
ch = '\0';
• String - a sequence of zero or more characters enclosed in double quote
marks
• C stings are null terminated
• This means that the last character in a string is the null character

C Strings (Character Arrays)


• If we have the text:
―John L. Johnson‖
―Hello there.‖
• There is a difference between 'A' and ―A‖
• The first one is character A and the second is string A Since strings are null
terminated, "A" represents two characters, 'A' and '\0'

C Strings (Character Arrays)


• "Hello" represents six characters, 'H', 'e', 'l', 'l', 'o', and '\0' To store 'A' we
need only one memory cell of the type char, while to store "A", we need two
memory cells of the type char, one for 'A' and the other for '\0' To store the
string "HELLO" we need six memory cells of the type char
• Consider the statement
char name[16];

C Strings (Character Arrays)


• Since C strings are null terminated and name has sixteen components, the
largest string that can be stored in name is 15 If you store a string of
length, say 10 in name, the first 11 components of name are used and the
last 5 are left unused
• If we have the statement:
char name[16] = {'J', 'o', 'h', 'n', '\0'};

C Strings (Character Arrays)


• During char array variable declaration, the string notation to be used is
char name[16] = "John"; //Line A
• The statement
char name[] = "John"; //Line B
declares a string variable name of length large enough, that is, 5 (here)
and stores "John" in it
• Both statements stores "John" in name
• The size of name in the statement in Line A is 16 where it is 5 in Line B

String Comparison
• C-strings are compared character by character using the collating sequence of
the system
• If we are using the ASCII character set
• 1. The string "Air" is smaller than the string "Boat"
• 2. The string "Air" is smaller than the string "An"
• 3. The string "Bill" is smaller than the string "Billy"

Start here Page 45


• 4. The string "Hello" is smaller than "hello"

Reading and Writing Strings


• String Input
• Since aggregate operations are allowed for string input, the statement cin>>
name; will store the next input string into name
• Strings that contain blanks cannot be read using the extraction operator >>
• To read strings with blanks, the general form (syntax) of the get function
together with an input stream variable, such as cin is:
cin.get(str,m+1);
• This statement stores the next m characters or until the newline character '\n'
is found into str but the newline character is not stored in str

Reading and Writing Strings


• If the input string has fewer than m characters, then the reading stops at the
newline character
• String Output
• The statement cout<<name; will output the content of name on the screen
• The insertion operator << continues to write the contents of name until it
finds the null character
• If name does not contain the null character, then we will see strange output
since << continues to output data from memories adjacent to name until '\0'
is found

Input/Output Files
• Values (strings) of the type string are not null terminated
• Variables of type string can be used to read and store the names of
input/output files
• The argument to the function open must be a null terminated string, that is a
C string
• If we use a variable of the type string to read the name of an input/output file
and then use this variable to open a file, the value of the variable must first
be converted to a C-string (null-terminated string)

Input/Output Files
• The header file string contains the function c_str, which converts a value of
the type string to a null-terminated character array (C-string)
• The syntax to use the function c_str is:
strVar.c_str()
where strVar is a variable of the type string

Parallel Arrays
• Two (or more) arrays are called parallel if their corresponding components
hold related information
• For example:
int studentId[50];
char courseGrade[50];

Start here Page 46


Two-Dimensional Arrays
• Two-dimensional Array - a two-dimensional array is a collection of a fixed
number of components arranged in two dimensions, and all components are
of the same type
• The syntax for declaring a two-dimensional array is:
dataType arrayName[intexp1][intexp2];
where intexp1 and intexp2 are expressions yielding positive integer
values
• The two expressions intexp1 and intexp2 specify the number of rows and the
number of columns, respectively, in the array

Accessing Array Components


• The syntax to access a component of a two-dimensional array is:
arrayName[indexexp1][indexexp2]
where indexexp1 and indexexp2 are expressions yielding nonnegative
integer values
• indexexp1 specifies the row position and indexexp2 specifies the column
position

Initialization
• Like one-dimensional arrays, two-dimensional arrays can be initialized when
they are declared
• To initialize a two-dimensional array when it is declared
• 1. The elements of each row are enclosed within braces and separated by
commas.
• 2. All rows are enclosed within braces.
• 3. For number arrays, if all components of a row are not specified, the
unspecified components are initialized to zero.

Processing Two-dimensional Arrays


• A two-dimensional array can be processed in three different ways:
• 1. Process the entire array
• 2. Process a particular row of the array, called row processing
• 3. Process a particular column of the array, called column processing
• Each row and each column of a two-dimensional array is a one-dimensional
array
• When processing a particular row or column of a two-dimensional array we
use algorithms similar to process one-dimensional arrays

Initialization
• This for loop initializes row four to zero:
row = 4;
for(col = 0; col < columns; col++)
matrix[row][col] = 0;
• To initialize the entire matrix, we can also put the first index (row position) in
a loop
These nested for loops initialize each component of matrix to 0:
Start here Page 47
• These nested for loops initialize each component of matrix to 0:
for(row = 0; row < rows; row++)
for(col = 0; col < columns; col++)
matrix[row][col] = 0;

Print
• The following nested for loops print the components of matrix, one row per
line:
for(row = 0; row < rows; row++)
{
for(col = 0; col < columns; col++)
cout<<setw(5)<<matrix[row][col]<<" ";
cout<<endl;
}

Input
• This for loop inputs data in row number 4 of matrix:
row = 4;
for(col = 0; col < columns; col++)
cin>>matrix[row][col];
• By putting the row number in a loop we can input data in each component of
the matrix
for(row = 0; row < rows; row++)
for(col = 0; col < columns; col++)
cin>>matrix[row][col];

Two-dimensional Arrays
• Two-dimensional arrays can be passed as parameters to a function and they
are passed by reference The base address, that is, the address of the first
component of the actual parameter is passed to the formal parameter If
matrix is the name of a two-dimensional array, then matrix[0][0] is the first
component of matrix

Two-dimensional Arrays
• When storing a two-dimensional array in the computer’s memory, the row
order form is used This means that the first row is stored first, followed by
the second row, which is followed by the third row and so on When
declaring a two-dimensional array as a formal parameter, we can omit the
size of the first dimension, but not the second
• The number of columns must be specified

Multi-dimensional Arrays
• Array - a collection of a fixed number of elements (called components)
arranged in n dimensions (n >= 1), called an n-dimensional array The
general syntax of declaring an n-dimensional array is:
dataType arrayName[intExp1][intExp2]...[intExpn];
where intExp1, intExp2, … , and intExpn are constant expressions
yielding positive integer values

Start here Page 48


yielding positive integer values

Multi-dimensional Arrays
• The syntax of accessing a component of an n-dimensional array is:
arrayName[indexExp1][indexExp2]...[indexExpn]
where indexExp1,indexExp2,..., and indexExpn are expressions yielding
nonnegative integer values. indexExpi gives the position of the array
component in the ith dimension

Multi-dimensional Arrays
• When declaring a multi-dimensional array as a formal parameter in a function,
we can omit the size of the first dimension but not the other dimensions As
parameters multi-dimensional arrays are passed by reference only and a
function cannot return a value of the type array There is no check if the
array indices are within bounds

Chapter 10
RECORDS (Structs)

Records (Structs)
• Struct - a collection of a fixed number of components in which components
are accessed by name is called a struct
• The components may be of different types
• The components of a struct are called the members of the struct A struct is
a definition not a declaration; no memory is allocated
• Memory is allocated when we declare variables

Struct Syntax
• The general form (syntax) of a struct is:
struct typeName
{
dataType1 identifier1;
dataType2 identifier2;
.
.
.
dataTypen identifiern;
};

Accessing struct Members


• The syntax for accessing a struct member is:
structVariableName.MemberName
• The . (dot) is an operator called the member access operator

Assignment and Comparison


• The value of one struct variable can be assigned to another struct variable of
the same type using an assignment statement
struct variables are compared member-wise

Start here Page 49


• struct variables are compared member-wise
• To compare the values of student and newStudent, you must compare them
member-wise, as follows:
if(student.firstName == newStudent.firstName &&
student.lastName == newStudent.lastName)
.
.
.

Input/Output
• There are no aggregate input/output operations on struct Data in a struct
variable must be read one member at a time Contents of a struct must be
written one member at a time

struct Variables and Functions


• A struct variable can be passed as a parameter either by value or by
reference
• A function can return a value of the type struct

Arrays in Structs
• The two things that are associated with a list are the values (elements) and
the length of the list
• In the searching and sorting functions that we discussed, we needed to pass
these two things separately to the function
• Because the values and the length are both related to a list, we can define a
struct containing both the items
• We need to pass only one parameter, not two

Chapter 11
CLASSES AND DATA ABSTRACTION

Classes
• A class is a collection of a fixed number of components
• The components of a class are called members of the class
• The general syntax of defining a class is:
class classIdentifier
{
classMemberList

Start here Page 50


classMemberList
};
• A member of a class can either be a variable (that is, to store some data) or a
function

Classes
• If a member of a class is a variable, it is declared just like any other variable
• In the definition of the class, you cannot initialize a variable when you declare
it
• If a member of a class is a function, typically the function prototype is used to
define that member
• A missing semicolon, therefore, will result in a syntax error

Classes
• If a member of a class is a function,
• it can (directly) access any member of the class—data members and function
members
• when you write the definition of the member function, you can directly access
any data member of the class without passing it as a parameter
• the only obvious condition is that you must declare an identifier before you
can use it
• Class is a reserved word and it only defines a data type, no memory is
allocated
• The semicolon after the right brace is part of the syntax

Classes
• The members of a class are classified into three categories:
• private
• public
• protected
• Following are some facts about public and private members of a class:
• By default, all members of a class are private
• If a member of a class is private, you cannot access it outside the class

Classes
• A public member is accessible outside the class To make a member of a
class public, you use the label public with a colon In C++, private,
protected, and public are reserved words

Variable (Object) Declaration


• Once a class is defined, you can declare variables of that type
• In C++ terminology, a class variable is called a class object or class instance
• To become familiar with this terminology, we will use the term class object, or
simply object, for a class variable
• The syntax for declaring a class object is the same as that for declaring any
other variable
clockType myClock;
clockType yourClock;
Start here Page 51
clockType yourClock;

Accessing Class Members


• Once an object is declared, it can access the public members of a class The
general syntax to access the member of a class is:
classVariableName.memberName
• In C++, the dot, . (period), is an operator called the member access operator

Built-in Operations on Classes


• Most of C++’s built-in operations do not apply to classes
• Arithmetic operators cannot be used to perform arithmetic operations on class
objects unless they are overloaded
• Also, you cannot use relational operators to compare two class objects for
equality
• The two built-in operations that are valid for class objects are member access
(.) and assignment (=)

Class Scope
• A class object has the same scope as other variables
• A member of a class is local to the class
• We access a class member outside the class by using the class object name
and the member access operator (.)

Functions and Classes


• Class objects can be passed as parameters to functions and returned as
function values As parameters to functions, classes can be passed either by
value or by reference If a class object is passed by value, the contents of
the data members of the actual parameter are copied into the corresponding
data members of the formal parameter

Reference Parameters & Variables


• As a parameter, a class object can be passed by value
• If a variable is passed by value, the corresponding formal parameter receives
a copy of the data of the variable
• This operation might require, in addition to a large amount of storage space,
a considerable amount of computer time to copy the value of the actual
parameter into the formal parameter

Reference Parameters & Variables


• If a variable is passed by reference, the formal parameter receives only the
address of the actual parameter
• Therefore, an efficient way to pass a variable as a parameter is by reference
• If a variable is passed by reference, then when the formal parameter
changes, the actual parameter also changes
• You can pass a variable by reference and still prevent the function from
changing its value, by using the keyword const in the formal parameter
declaration

Start here Page 52


Constructors
• Constructors
• We can guarantee the initialization of the data members of a class by using
constructors
• There are two types of constructors:
• with parameters
• without parameters
• The constructor without parameters is called the default constructor
• A constructor that has no parameters, or has all default parameters, is called
the default constructor

Constructors
• 1. The name of a constructor is the same as the name of the class
• 2. A constructor:
• even though it is a function, has no type
• it is neither a value-returning function nor a void function
• 3. A class can have more than one constructor, however, all constructors of a
class have the same name
• 4. If a class has more than one constructor, they must have different sets of
parameters

Constructors
• 5. Constructors:
• are automatically executed when a class variable enters its scope
• since they have no types, they cannot be called like other functions
• 6. Which constructor executes depends on the type of values passed to the
class variable when the class variable is declared

Invoking a Constructor
• A constructor is automatically executed when a class variable is declared A
class might have more than one constructor, including the default constructor

Invoking the Default Constructor


• The syntax to invoke the default constructor is:
className classVariableName;
• The statement:
clockType yourClock;
declares yourClock to be a variable of the type clockType
• In this case, the default constructor is executed and the data members of
yourClock will be initialized to zero

Constructor with Parameters


• The syntax to invoke a constructor with parameters is:
className classVariableName(argument1,
argument2,. . . );
where argument1, argument2, etc. is either a variable or an expression

Start here Page 53


Constructor with Parameters
• 1. The number of arguments and their type should match the formal
parameters (in the order given) of one of the constructors
• 2. If the type of the arguments do not match the formal parameters of any
constructor (in the order given), C++ will use type conversion and look for
the best match
• For example,
• an integer value might be converted to a floating-point value with zero
decimal part
• an ambiguity will result in a compile-time error

Arrays
• If a class has constructors and you declare an array of class objects, the class
must have the default constructor The default constructor is used to
initialize each (array) class object
• For example:
clockType clocks[100];

Destructors
• Like constructors, destructors are also functions
• The name of a destructor is the character '~' followed by the name of the
class
• The name of the destructor for the class clockType is:
~clockType();
• A class can have only one destructor and it has no parameters
• The destructor is automatically executed when the class object goes out of
scope

Abstract Data Types


• The data type clockType has three data members and the following basic
operations:
• 1. Set the time
• 2. Return the time
• 3. Print the time
• 4. Increment the time by one second
• 5. Increment the time by one minute
• 6. Increment the time by one hour
• 7. Compare the two times to see whether they are equal

Abstract Data Types


• Abstract Data Type (ADT) - a data type that specifies the logical properties
without the implementation details
• An ADT has three things associated with it
• The name of the ADT, called type name
• The set of values belonging to the ADT, called domain
• The set of operations on the data

Start here Page 54


A Struct Versus a Class


• By default the members of a struct are public
• By default the members of a class are private
• The member access specifier private can be used in a struct to make a
member private
• Both C++ classes and structs have the same capabilities
• Most programmers restrict their use of structures to adhere to their C-like
structure form
• If all of the data members of a class are public and the class has no member
functions, typically a struct is used to group these members

Information Hiding
• The header file has an extension h
• The implementation file has an extension cpp
• The implementation file must include the header file via the include statement
In an include statement, user-defined header files are enclosed in double
quotes while system-provided header files are enclosed between angular
brackets

Files
• Visual C++, C++ Builder, and CodeWarrior put the editor, compiler, and
linker all into one package
• With one command, the program is compiled and linked with the other
necessary files
• These systems also manage multiple file programs in the form of a project
• A project consists of several files, called the project files

Files
• These systems usually have a command, called build, rebuild, or make
When the build, rebuild, or make command is applied to a project, the
system automatically compiles and links all files required to create the
executable code When one or more files in the project change, you can use
these commands to recompile and relink the files

Chapter 12
INHERITANCE AND COMPOSITION

Inheritance and Composition


• The two common ways to relate two classes in a meaningful way are:
• 1. Inheritance (―is-a‖ relationship)
• 2. Composition (―has-a‖ relationship)

Inheritance
• Design a class, partTimeEmployee, to implement and process the
characteristics of a part-time employee
• Every part-time employee has a name, pay rate, and number of hours worked
Every part-time employee is a person

Start here Page 55


• Every part-time employee is a person
• Rather than design the class partTimeEmployee from scratch, we want to be
able to extend the definition of the class personType by adding additional
members (data and/or function)

Inheritance
• We do not want to make the necessary changes directly to the class
personType—that is, edit the class personType, and add and/or delete
members
• We want to create the class partTimeEmployee without making any physical
changes to the class personType, by adding only the members that are
necessary
• The new class that we create from existing classes is called the derived class
and the existing classes are called the base classes

Inheritance
• Single inheritance- the derived class is derived from a single base class
• Multiple inheritance- the derived class is derived from more than one base
class
• Inheritance can be viewed as a tree-like, or hierarchical, structure wherein a
base class is shown with its derived classes
• The word public in a heading, called the member access specifier, specifies
that all public members of the class shape are inherited as public members by
the class circle

Inheritance

Facts
• The following facts about the base and the derived classes should be kept in
mind:
• 1. The private members of the base class are private to the base class; hence,
the members of the derived class cannot directly access them
• 2. The public members of a base class can be inherited either as public
members or as private members by the derived class
• 3. The derived class can include additional data and/or function members

Facts

Start here Page 56


Facts
• 4. The derived class can redefine the public member functions of the base
class. However, this redefinition applies only to the objects of the derived
class, not to the objects of the base class
• 5. All data members of the base class are also data members of the derived
class. Similarly, the member functions of the base class (unless redefined) are
also the member functions of the derived class

Constructors
• A derived class can have its own private data members
• Member functions of the derived class cannot directly access the private
members of the base class
• The constructors of the derived class can (directly) initialize only the private
data members of the derived class
• When a derived class object is declared, it must also automatically execute
one of the constructors of the base class

Constructors
• The execution of a derived class’s constructor must trigger the execution of
one of the base class’s constructors A call to the base class’s constructor is
specified in the heading part of the derived class constructor’s definition

Multiple Inclusions
• Suppose that the header file testA.h includes the file test.h to make use of the
identifiers one and two
• The preprocessor first includes the header file test.h and then the header file
testA.h
• When the header file testA.h is included, because it contains the preprocessor
directive #include "test.h", the header file test.h will be included twice in the
program
• The second inclusion of the header file test.h will result in compile-time
errors, such as identifier one already being declared
• To avoid multiple inclusion of a file in a program we use certain preprocessor
commands in the header file

Stream Classes

Stream Classes
Start here Page 57
Stream Classes
• The class ios is the base class for all stream classes
• Classes istream and ostream are directly derived from the class ios
• The class ifstream is derived from the class istream, and the class ofstream is
derived from the class ostream
• The class ios contains formatting flags and member functions to access
and/or modify the setting of these flags

Stream Classes
• To identify the I/O status, the class ios contains an integer status word This
integer status word provides a continuous update reporting the status of the
stream The classes istream and ostream are responsible for providing the
operations for the data transfer between memory and devices

Stream Classes
• The class istream defines the extraction operator, >>, and functions such as
get and ignore
• The class ostream defines the insertion operator, <<, which is used by the
object cout
• The class ifstream is derived from the class istream to provide the file input
operations
• The class ofstream is derived from the class ostream to provide the file output
operations

Stream Classes
• Objects of the type ifstream are used for file input Objects of the type
ofstream are used for file output The header file fstream contains the
definition of the classes ifstream and ofstream

Protected Members of a Class


• The private members of a class are private to the class and cannot be directly
accessed outside the class
• The derived class cannot access private members of a class
• It is sometimes necessary for a derived class to access a private member of a
base class
• If you make a private member become public, then anyone can access that
member

Protected Members of a Class


• For a base class to give access to a private member to its derived class and
still prevent its direct access outside the class, you must declare that member
under the memberAccessSpecifier protected The accessibility of a protected
member of a class is in between public and private A derived class can
directly access the protected member of a base class

Inheritance
• 1. If memberAccessSpecifier is public, then
a. The public members of A are public members of B and they can be directly

Start here Page 58


• a. The public members of A are public members of B and they can be directly
accessed in class B
• b. The protected members of A are protected members of B and they can be
directly accessed by the member functions (and friend functions) of B
• c. The private members of A are hidden in B and they can be accessed by the
member functions (and friend functions) of B through the public or protected
members of A

Inheritance
• 2. If memberAccessSpecifier is protected, then
• a. The public members of A are protected members of B and they can be
accessed by the member functions (and friend functions) of B
• b. The protected members of A are protected members of B and they can be
accessed by the member functions (and friend functions) of B
• c. The private members of A are hidden in B and they can be accessed by the
member functions (and friend functions) of B through the public or protected
members of A

Inheritance
• 3. If memberAccessSpecifier is private, then
• a. The public members of A are private members of B and they can be
accessed by the member functions (and friend functions) of B
• b. The protected members of A are private members of B and they can be
accessed by the member functions (and friend functions) of B
• c. The private members of A are hidden in B and they can be accessed by the
member functions (and friend functions) of B through the public or protected
members of A

Composition
• In composition one or more member(s) of a class is an object of another class
type
• Composition is a ―has-a‖ relation
• The arguments to the constructor of a member-object are specified in the
heading part of the definition of the constructor of the class
• Member-objects of a class are constructed in the order they are declared, not
in the order they are listed in the constructor’s member initialization list, and
before the enclosing class objects are constructed

OOD and OOP


• The fundamentals of Object-Oriented Design (OOD) are:
• 1. Encapsulation—combine data and operations on data in a single unit
• 2. Inheritance—create new objects from existing objects
• 3. Polymorphism—the ability to use the same expression to denote different
operations
• In OOD an object is a fundamental entity, while in structured programming a
function is a fundamental entity

OOD and OOP


Start here Page 59
OOD and OOP
• In OOD we debug objects, while in structured programming we debug
functions
• In structured programming a program is a collection of interacting functions,
while in OOD a program is a collection of interacting objects
• OOD encourages code reuse
• In structured programming the programmer is action-oriented, while in OOD
the programmer is object-oriented

OOD and OOP


• Object-oriented programming (OOP) implements OOD
• C++ supports OOP through the use of classes
• A polymorphic function or operator has many forms
• A function name and operators can be overloaded
• Templates provide parametric polymorphism
• C++ provides virtual functions as a means to implement polymorphism in an
inheritance hierarchy

OOD and OOP


• Objects are created when class variables are declared
• Objects interact with each other via function calls
• Every object has an internal state and external state
• The private members form the internal state and the public members form
the external state
• Only the object can manipulate its internal state

Classes, Objects, & Operations


• We begin with a description of the problem and then identify all of the nouns
and verbs From the list of nouns we choose our classes, and from the list of
verbs we choose our operations Suppose that we want to write a program
that calculates and prints the volume and surface area of a cylinder

Chapter 13
POINTERS, CLASSES, LISTS, AND VIRTUAL FUNCTIONS

Pointer Variables
• Pointer variable - a variable whose content is a memory address
• Declaring Pointer Variables
• The general syntax of declaring a pointer variable is
dataType *identifier;
int *p;
char *ch;

Pointer Variables
• The statement int *p; is equivalent to the statement int* p; which is
equivalent to the statement int * p;
• The character * can appear anywhere between the data type name and the
variable name

Start here Page 60



variable name
int* p, q;
• Only p is the pointer variable, not q. Here q is an int variable

Pointer Variables
• To avoid confusion, we prefer to attach the character * to the variable name
int *p, q;
• The following statement declares both p and q to be pointer variables of the
type int
int *p, *q;

The Address Of Operator (&)


• The ampersand, &,
• is called the address of operator
• is a unary operator that returns the address of its operand

The Dereferencing Operator (*)


• C++ also uses * as a unary operator
• When used as a unary operator, *,
• commonly referred to as the dereferencing operator or indirection operator
• refers to the object to which its operand (that is, a pointer) points

Dynamic Variables
• Variables that are created during program execution are called dynamic
variables
• With the help of pointers, C++ creates dynamic variables
• New and delete, to create and destroy dynamic variables, respectively
• When a program requires a new variable, the operator new is used
• When a program no longer needs a dynamic variable, the operator delete is
used
• In C++, new and delete are reserved words

The Operator new


• The syntax to use the operator new is
new dataType; //to allocate a single variable
new dataType[intExp]; //to allocate an array of
variables
where intExp is any expression evaluating to a positive integer
• The operator new allocates memory (a variable) of the designated type and
returns a pointer to it—that is, the address of this allocated memory
• The allocated memory is uninitialized

The Operator delete


• The C++ operator delete is used to destroy dynamic variables
• The syntax of delete has two forms:
delete pointer; //to destroy a single dynamic variable
delete [] pointer; //to destroy a dynamically //created array
The statements

Start here Page 61


delete [] pointer; //to destroy a dynamically //created array
• The statements
delete p;
delete [] name;
deallocate memory referenced by the pointers p and name

Operations on Pointer Variables


• Assignment - value of one pointer variable can be assigned to another pointer
variable of the same type
• Relational operations - two pointer variables of the same type can be
compared for equality, and so on
• Some limited arithmetic operations
• integer values can be added and subtracted from a pointer variable
• value of one pointer variable can be subtracted from another pointer variable

Operations on Pointer Variables


• When an integer is added to a pointer variable, the value of the pointer
variable is incremented by the integer times the size of the memory that the
pointer is pointing to When an integer is subtracted from a pointer variable,
the value of the pointer variable is decremented by the integer times the size
of the memory to which the pointer is pointing

Dynamic Arrays
• An array created during the execution of a program is called a dynamic array
• To create a dynamic array, we use the second form of the new operator
• The statement int *p; declares p to be a pointer variable of the type int
• The statement p = new int[10]; allocates 10 contiguous memory locations,
each of the type int, and stores the address of the first memory location into
p

Functions and Pointers


• A pointer variable can be passed as a parameter to a function either by value
or by reference
• To make a pointer a reference parameter in a function heading, * appears
before the & between the data type name and the identifier
void example(int* &p, double *q)
{
...
}
• Both p and q are pointers
• The parameter p is a reference parameter; the parameter q is a value
parameter
• A function can return a value of the type pointer

Shallow copy vs Deep copy


• In a shallow copy, two or more pointers of the same type point to the same
memory; that is, they point to the same data In a deep copy, two or more
pointers have their own data

Start here Page 62


The Destructor
• The object objectOne has a pointer data member p
• Suppose that during program execution the pointer p creates a dynamic array
• When objectOne goes out of scope, all data members of objectOne are
destroyed
• However, p created a dynamic array, and dynamic memory must be
deallocated using the operator delete

The Destructor
• If the pointer p does not use the delete operator to deallocate the dynamic
array, the memory space of the dynamic array would stay marked as
allocated, even though no one can access it How do we ensure that when p
is destroyed, the dynamic memory created by p is also destroyed?

The Destructor
• If a class has a destructor, the destructor automatically executes whenever a
class object goes out of scope We can put the necessary code in the
destructor to ensure that when objectOne goes out of scope, the memory
created by the pointer p is deallocated

The Assignment Operator


• To avoid shallow copying of data for classes with a pointer data member,
C++ allows the programmer to extend the definition of the assignment
operator
• This process is called overloading the assignment operator
• Once the assignment operator is properly overloaded, both the objects
objectOne and objectTwo have their own data, as shown in Figure 14-19

The Assignment Operator

The Copy Constructor


• Consider the following statement:
pointerDataClass objectThree(objectOne);
• objectThree is being declared and is also being initialized using the value of
objectOne
This initialization is called the default member-wise initialization

Start here Page 63


• This initialization is called the default member-wise initialization
• The default member-wise initialization is due to the constructor, called the
copy constructor provided by the compiler
• This default initialization would lead to a shallow copying of the data

The Copy Constructor


• If a class has pointer data members:
• during object declaration, the initialization of one object using the value of
another object would lead to shallow copying of data if the default member-
wise copying of data is allowed
• If, as a parameter, an object is passed by value and the default member-wise
copying of data is allowed, it would lead to shallow copying of data
• In both cases, to force each object to have its own copy of the data, we must
override the definition of the copy constructor provided by the compiler

The Copy Constructor


• This is usually done by putting a statement that includes the copy constructor
in the definition of the class, and then writing the definition of the copy
constructor For the class pointerDataClass, we can overcome this shallow
copying of data problem by including the copy constructor in the class
pointerDataClass

The Copy Constructor


• The copy constructor automatically executes in two situations:
• when an object is declared and initialized by using the value of another object
• when, as a parameter, an object is passed by value
• General Prototype Syntax:
• classType (const classType& objCopySource);

Array-Based Lists
• List - a collection of elements of the same type
• The length of a list is the number of elements in the list
• Operations performed on a list are:
• Create the list and initialize to an empty state
• Determine whether the list is empty
• Determine whether the list is full
• Find the size of the list
• Destroy, or clear the list

Array-Based Lists
• Operations performed on a list are:
• Determine whether an item is the same as a given list element
• Insert an item in the list at the specified location
• Remove an item from the list at the specified location
• Replace an item at the specified location with another item
• Retrieve an item from the list at the specified location
• Search the list for a given item

Start here Page 64


Lists
• Lists are stored as an array
• The size of the array can be specified when a list object is declared
• To maintain and process the list in an array, we need three variables:
• The array holding the list elements
• A variable to store the length of the list (that is, the number of elements
currently in the array)
• A variable to store the size of the array (that is, the maximum number of
elements that can be stored in the array)

Inheritance, Pointers, And Virtual Functions


• C++ allows the user to pass an object of a derived class to a formal
parameter of the base class type
• In compile-time binding, the necessary code to call a specific function is
generated by the compiler
• Compile-time binding is also known as static binding
• When the body of the function two executes, logically the print function of
object two should execute, which is not the case

Inheritance, Pointers, And Virtual Functions


• C++ corrects this problem by providing the mechanism of virtual functions
• The binding of virtual functions occurs at program execution time, not at
compile time
• This kind of binding is called run-time binding
• In run-time binding, the compiler does not generate code to call a specific
function
• Instead, it generates enough information to enable the run-time system to
generate the specific code for the appropriate function call
• Run-time binding is also known as dynamic binding

Address Of Operator & Classes


• The address of operator is also used to create aliases to an object
• Consider the following statements:
int x;
int &y = x;
• x and y refer to the same memory location
• y is like a constant pointer variable
• The statement y = 25; sets the value of y and hence of x to 25
• Similarly the statement x = 2 * x + 30; updates the value of x and hence of y

Chapter 14
OVERLOADING AND TEMPLATES

Operator Overloading
• The only built-in operations on classes are the assignment operator and the
member selection operator Therefore, other operators cannot be applied,
directly, on class objects C++ allows the programmer to extend the

Start here Page 65


directly, on class objects C++ allows the programmer to extend the
definitions of most of the operators to work with classes In C++’s
terminology, this is called operator overloading

Operator Overloading
• C++ allows the user to overload most of the operators to work effectively in a
specific application
• C++ does not allow the user to create new operators
• Most of the existing operators can be overloaded to manipulate class objects
• In order to overload an operator we must write functions

Operator Overloading
• The name of the function that overloads an operator is the reserved word
operator followed by the operator to be overloaded
• The following function name overloads >=
operator>=
• Operator function: The function that overloads an operator

Syntax for Operator Functions


• The syntax of the heading of an operator function is:
returnType operator operatorSymbol(arguments)
• The operator function is a value-returning function
• In C++, operator is a reserved word
• To overload an operator for a class:
• 1. Include the function to overload the operator (that is, the operator
function) in the definition of the class
• 2. Write the definition of the operator function

Some Restrictions
• When overloading an operator the following should be kept in mind
• 1. You cannot change the precedence of an operator
• 2. The associativity cannot be changed
• 3. Default arguments cannot be used with an overloaded operator
• 4. You cannot change the number of arguments that an operator takes

Some Restrictions
• 5. You cannot create new operators
• Only existing operators can be overloaded
• The operators that cannot be overloaded are
. .* :: ?: sizeof
• 6. The meaning of how an operator works with built-in types, such as int,
remains the same
• 7. Operators can be overloaded either for objects of the user-defined type, or
for a combination of objects of the user-defined type and objects of the built-
in type

this Pointer
Every object of a class maintains a (hidden) pointer to itself

Start here Page 66


• Every object of a class maintains a (hidden) pointer to itself
• The name of this pointer is this
• In C++, this is a reserved word
• When an object invokes a member function, the this pointer of the object is
referenced by the member function

Friend Functions of Classes


• A function that is defined outside the scope of a class is called a friend
function A friend function is a nonmember function of the class, but has
access to the private data members of the class To make a function friend
to a class, the reserved word friend precedes the function prototype in the
class definition

Friend Functions of Classes


• The word friend appears only in the function prototype (in the class
definition), not in the definition of the friend function When writing the
definition of the friend function, the name of the class and the scope
resolution operator does not precede the name of the friend function in the
function heading

Operator Functions
• 1. The function that overloads any of the operators (), [], ->, or = for a class
must be declared as a member of the class
• 2. Suppose an operator op is overloaded for a class, say OpOverClass
• a. If the leftmost operand of op is an object of a different type (that is, not of
the type OpOverClass), the function that overloads the operator op for
OpOverClass must be a nonmember—that is, a friend of the class
OpOverClass

Operator Functions
• b. If the operator function that overloads the operator op for the class
OpOverClass is a member of the class OpOverClass, then when applying op
on objects of the type OpOverClass, the leftmost operand of op must be of
the type OpOverClass
• Except for some of the operators, as explained above, most of the operators
can be overloaded either as member functions or as nonmember functions

Binary Operators
• Suppose that the binary operator + is overloaded for the class OpOverClass
Overloading + as a Member Function
• Suppose that + is overloaded as a member function of the class OpOverClass
• The name of the function to overload + for the class OpOverClass is
operator+

Binary Operators
• Since x and y are objects of the type OpOverClass, we can perform the
operation
x+y

Start here Page 67


• x+y
• The compiler translates this expression into the following expression:
• x.operator+(y)
• In this expression, there is only one argument to the function operator+,
which is y

Binary Operators
• In the above statement, operator+ has direct access to the private members
of the object x
• The first argument to operator+ is the object that is invoking the function
operator+ and the second argument is passed as a parameter to this function
• Suppose that the operator + adds the corresponding data members of the
objects
• The result of the expression x + y is an object of the type OpOverClass

Binary Operators
• The return type of the operator function operator+ is of the type OpOverClass
• The function prototype of operator+ in the definition of the class OpOverClass
is:
OpOverClass operator+(const OpOverClass&) const;

General Syntax
• Function Prototype (to be included in the definition of the class):
returnType operator op(className);
• op stands for the binary operator to be overloaded
• returnType is the type of the value returned by the function
• className is the name of the class for which the operator is being overloaded

Overloading Relational Operators


• We overload the equality operator, ==, for the class OpOverClass
• Since the result of a relational operator is either true or false, the returnType
of the function operator== is Boolean
• The syntax of the function prototype to be included in the definition of the
class OpOverClass is:
bool operator==(const OpOverClass&) const;

Binary Operators & Nonmember Functions


• Suppose that + is overloaded as a nonmember function of the class
OpOverClass
• Suppose that the following operation is to be performed
x+y
• This expression is compiled as:
operator+(x,y)
• The function operator+ has two arguments

Binary Operators & Nonmember Functions


• The function operator+ is neither a member of the object x nor a member of

Start here Page 68



the object y
• The objects to be added are passed as arguments to the function operator+
• To include the operator function operator+ as a nonmember of the class in
the definition of the class the reserved word friend must appear before the
function heading
• The function operator+ must have two arguments

Binary Operators & Nonmember Functions


• To include operator+ as a nonmember in the definition of the class
OpOverClass its prototype in the definition of OpOverClass is
friend OpOverClass operator+(const OpOverClass&,
const OpOverClass&);

General Syntax
• Function Prototype (to be included in the definition of the class):
friend returnType operator op(const className&,
const className&);
• op stands for the binary operator to be overloaded
• returnType is the type of the value returned by the function
• className is the name of the class for which the operator is being overloaded

Overloading Relational Operators as Member Functions


• We overload the equality operator, ==, for the class OpOverClass
• Since the result of a relational operator is either true or false, the returnType
of the function operator== is Boolean
• The syntax of the function prototype to be included in the definition of the
class OpOverClass is:
bool operator==(const OpOverClass&) const;

Binary Operators as Nonmember Functions


• If + is overloaded as a nonmember function of the class OpOverClass and the
following operation is to be performed:
x+y
• This expression is compiled as operator+(x,y)
• The function operator+ has two arguments
• The function operator+ is neither a member of the object x nor a member of
the object y
• The objects to be added are passed as arguments to the function operator+

Binary Operators as Nonmember Functions


• To include the operator function operator+ as a nonmember of the class in
the definition of the class the reserved word friend must appear before the
function heading
• The function operator+ must have two arguments
• To include operator+ as a nonmember in the definition of the class
OpOverClass its prototype in the definition of OpOverClass is:
friend OpOverClass operator+(const OpOverClass&,
const OpOverClass&);
Start here Page 69
friend OpOverClass operator+(const OpOverClass&,
const OpOverClass&);

General Syntax
• Function Prototype (to be included in the definition of the class):
friend returnType operator op(const className&,
const className&);
• op stands for the binary operator to be overloaded
• returnType is the type of the value returned by the function
• className is the name of the class for which the operator is being overloaded

Overloading Relational Operators


• We overload the equality operator, ==, for the class OpOverClass
• The return type of the function operator== is Boolean
• Function Prototype
friend bool operator==(const OpOverClass&,
const OpOverClass&);

General Syntax
• Function Prototype (to be included in the definition of the class):
friend bool operator op(const className&,
const className&);
• op is the relational operator that is being overloaded
• className is the name of the class for the operator op is being overloaded

Overloading << & >> Operators


• The operator function that overloads the insertion operator << or the
extraction operator >> for a class must be a nonmember of that class
• Consider the following expression.
cin>>x
• In this expression, the leftmost operand of >> (cin) is an istream variable,
not an object of the type OpOverClass

Overloading << & >> Operators


• Since the leftmost operand of >> is not an object of the type OpOverClass,
the operator function that overloads the extraction operator for OpOverClass
must be a nonmember of the class OpOverClass Similarly, the operator
function that overloads the stream insertion operator for OpOverClass must
be a nonmember function of OpOverClass

Overloading Unary Operators


• 1. If the operator function is a member of the class, it has no parameters
2. If the operator function is a nonmember, that is, a friend function of
the class it has one parameter

Overloading ++ and --
• The increment operator has two forms, pre-increment (++u) and post-
increment (u++), where u is a variable, say of the type int
With a pre-increment (++u), the value of u is incremented by 1 before using

Start here Page 70


• With a pre-increment (++u), the value of u is incremented by 1 before using
the value of u in an expression
• With a post-increment the value of u is used in the expression before it is
incremented by 1
• To overload the pre-increment operator, in the function definition first we
increment the value of the object and then use the this pointer to return the
value of the object

Overloading the
Post-Increment Operator
• Overload the post-increment operator for the class OpOverClass
• In both cases, pre- and post-increment, the name of the operator function is
the operator++
• To distinguish between pre- and post-increment operator overloading, we use
a dummy parameter (of the type int) in the function heading of the operator
function
• The function prototype for the post-increment operator for the class
OpOverClass is:
OpOverClass operator++(int);

Operator Overloading: Member Versus Nonmember


• Certain operators must be overloaded as member functions of the class, and
some must be overloaded as nonmember (friend) functions
• The binary arithmetic operator + can be overloaded as a member function or
a nonmember function
• If you overload + as a member function, then the operator + has direct
access to the data members of one of the objects, and you need to pass only
one object as a parameter

Operator Overloading: Member Versus Nonmember


• If you overload + as a nonmember function, then you must pass both objects
as parameters Overloading + as a nonmember could require additional
memory and computer time to make a local copy of the data For efficiency
purposes, wherever possible, you should overload operators as member
functions

Templates
• By using templates we write a single code for a set of related functions- called
function template and related classes- called class template
• The syntax for templates is:
template <class Type>
declaration;
where Type is the type of the data and declaration is either a function
declaration or a class declaration

Templates
• In C++, template is a reserved word
The word class in the heading refers to any user-defined type or built-in type
Start here Page 71
• The word class in the heading refers to any user-defined type or built-in type
Type is referred to as a formal parameter to the template Just as variables
are parameters to functions, types (that is, data types) are parameters to
templates

Class Templates
• Class templates are used to write a single code segment for a set of related
classes
• Syntax:
template<class Type>
class declaration
• Class templates are called parameterized types because, based on the
parameter type, a specific class is generated
• A template instantiation can be created with either a built-in or user-defined
type
• The function members of a class template are considered function templates

Header File
• Until now, we have placed the definition of the class and the definition of the
member functions in separate files
• The object code was generated from the implementation file and linked with
the user code
• Passing parameters to a function has an effect at run time, whereas passing a
parameter to a class template has an effect at compile time

Header File
• We can no longer compile the implementation file independently of the client
code because
• the actual parameter to a class is specified in the client code
• the compiler cannot instantiate a function template without the actual
parameter to the template
• We could put the class definition and the definitions of the function templates
directly in the client code, or we could put the class definition and the
definitions of the function templates together in the same header file

Header File
• Another alternative is to put the class definition and the definitions of the
functions in separate files, but include a directive to the implementation file at
the end of the header file In either case, the function definitions and the
client code are compiled together We will put the class definition and the
function definitions in the same header file

Chapter 15
EXCEPTION HANDLING

Exceptions
• Exception: undesirable event detectable during program execution
If exceptions occurred during execution

Start here Page 72


• If exceptions occurred during execution
• Programmer-supplied code terminated the program or
• Program terminated with an appropriate error message
• Can add exception-handling code at the point where an error can occur

Handling Exceptions within a Program


• Function assert:
• Checks if an expression meets certain condition(s)
• If the conditions are not met, it terminates the program
• Example: division by 0
• If the divisor is zero, assert terminates the program with an error message

C++ Mechanisms of Exception Handling


• The try/catch block handles exceptions
• Exception must be thrown in a try block and caught by a catch block C++
provides support to handle exceptions via a hierarchy of classes

try/catch Block
• Statements that may generate an exception are placed in a try block The try
block also contains statements that should not be executed if an exception
occurs The try block is followed by one or more catch blocks

try/catch Block
• The catch block specifies the type of exception it can catch and contains an
exception handler If the heading of a catch block contains ... (ellipses) in
place of parameters, then this catch block can catch exceptions of all types

try/catch Block
• The general syntax of the try/catch block is:

Start here Page 73


try/catch Block
• If no exception is thrown in a try block
• All catch blocks for that try block are ignored
• Execution resumes after the last catch block
• If an exception is thrown in a try block, the remaining statements in that try
block are ignored

try/catch Block
• The program searches the catch blocks in order, looking for an appropriate
exception handler
• If the type of thrown exception matches the parameter type in one of the
catch blocks:
• Code of that catch block executes
• Remaining catch blocks are ignored

Throwing an Exception
• For try/catch to work, the exception must be thrown in the try block
• General syntax to throw an exception is:
throw expression;
where expression is a constant value, variable, or object

Throwing an Exception
• The object being thrown can be
• Specific object
• Anonymous object
• In C++, an exception is a value
• In C++, throw is a reserved word

Throwing an Exception

Order of catch Blocks


• Catch blocks can catch
• All exceptions of a specific type
• All types of exceptions
• A catch block with an ellipses (three dots) catches any type of exception
• In a sequence of try/catch blocks, if the catch block with an ellipses is
needed, then it should be the last catch block of that sequence

Using try/catch Blocks in a Program

Start here Page 74


Using C++ Exception Classes
• C++ provides support to handle exceptions via a hierarchy of classes
• The function what returns the string containing the exception object thrown
by C++’s built-in exception classes
• The class exception is the base class of the exception classes provided by
C++
• The class exception is contained in the header file exception

Using C++ Exception Classes


• Two classes derived from exception:
• logic_error
• runtime_error
• logic_error and runtime_error are defined in header file stdexcept
• The class invalid_argument deals with illegal arguments used in a function call

Using C++ Exception Classes


• The class out_of_range deals with the string subscript out_of_range error
The class length_error handles the error if a length greater than the
maximum allowed for a string object is used

Using C++ Exception Classes


• If the operator new cannot allocate memory space, it throws a bad_alloc
exception
• The class runtime_error deals with errors that occur only during program
execution
• Classes overflow_error and underflow_error
• Deal with arithmetic overflow and underflow exceptions
• Derived from the class runtime_error

Start here Page 75


Creating Your Own Exception Classes
• Programmers can create exception classes to handle exceptions not covered
by C++’s exception classes and their own exceptions
• C++ uses the same mechanism to process the exceptions you define as for
built-in exceptions
• You must throw your own exceptions using the throw statement
• Any class can be an exception class

Rethrowing and Throwing an Exception


• When an exception occurs in a try block, control immediately passes to one of
the catch blocks
• A catch block either
• Handles the exception or partially processes the exception and then rethrows
the same exception or
• Rethrows another exception for the calling environment to handle

Rethrowing and Throwing an Exception


• The general syntax to rethrow an exception caught by a catch block is:
throw;
(in this case, the same exception is rethrown) or:
throw expression;
where expression is a constant value, variable, or object

Rethrowing and Throwing an Exception


• The object being thrown can be
• A specific object
• An anonymous object
• A function specifies the exceptions it throws in its heading using the throw
clause

Exception Handling Techniques


• When an exception occurs, the programmer usually has three choices:
• Terminate the program
• Include code to recover from the exception
• Log the error and continue

Terminate the Program


• In some cases, it is best to let the program terminate when an exception
occurs For example, if the input file does not exist when the program
executes, then there is no point in continuing with the program The
program can output an appropriate error message and terminate

Fix the Error and Continue


• In some cases, you will want to handle the exception and let the program
continue For example, if a user inputs a letter in place of a number, the
input stream will enter the fail state You can include the necessary code to
keep prompting the user to input a number until the entry is valid

Start here Page 76


keep prompting the user to input a number until the entry is valid

Log the Error and Continue


• For example, if your program is designed to run a nuclear reactor or
continuously monitor a satellite, it cannot be terminated if an exception occurs
When an exception occurs, the program should write the exception into a
file and continue to run

Stack Unwinding
• When an exception is thrown in, say, a function, the function can do the
following:
• Do nothing
• Partially process the exception and throw the same exception or a new
exception
• Throw a new exception

Stack Unwinding
• In each of these cases, the function-call stack is unwound so that the
exception can be caught in the next try/catch block
• When the function call stack is unwound
• The function in which the exception was not caught and/or rethrown
terminates
• Memory for its local variables is destroyed

Stack Unwinding
• The stack unwinding continues until
• A try/catch handles the exception or
• The program does not handle the exception
• If the program does not handle the exception, then the function terminate is
called to terminate the program

C++ Programming:
Program Design Including
Data Structures, Third Edition
Chapter 16: Recursion

Recursive Definitions
•Recursion: solving a problem by reducing it to smaller versions of itself
• 0! = 1 (1)
n! = n x (n-1)! if n > 0 (2)
•The definition of factorial in equations (1) and (2) is called a recursive definition
•Equation (1) is called the base case
•Equation (2) is called the general case

Recursive Definitions (continued)


•Recursive definition: defining a problem in terms of a smaller version of itself
−Every recursive definition must have one (or more) base cases
−The general case must eventually reduce to a base case
−The base case stops the recursion

Start here Page 77


Recursive Algorithms
•Recursive algorithm: finds a solution by reducing problem to smaller versions of
itself
−Must have one (or more) base cases
•General solution must eventually reduce to a base case
•Recursive function: a function that calls itself
•Recursive algorithms are implemented using recursive functions

Recursive Functions
•Think of a recursive function as having infinitely many copies of itself
•Every call to a recursive function has
−Its own code
−Its own set of parameters and local variables
•After completing a particular recursive call
−Control goes back to the calling environment, which is the previous call

Recursive Functions (continued)


•The current (recursive) call must execute completely before control goes back to
the previous call
•Execution in the previous call begins from the point immediately following the
recursive call
•Tail recursive function: A recursive function in which the last statement executed
is the recursive call
−Example: the function fact

Start here Page 78


Direct and Indirect Recursion
•Directly recursive: a function that calls itself
•Indirectly recursive: a function that calls another function and eventually results in
the original function call

Infinite Recursion
•Infinite recursion: every recursive call results in another recursive call
−In theory, infinite recursion executes forever
•Because computer memory is finite:
−Function executes until the system runs out of memory
−Results in an abnormal program termination

Infinite Recursion (continued)


•To design a recursive function:
−Understand problem requirements
−Determine limiting conditions
−Identify base cases and provide a direct solution to each base case
−Identify general cases and provide a solution to each general case in terms of
smaller versions of itself

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

Memory allocation
•Whenever a function is called
−Memory space for its formal parameters and (automatic) local variables is
allocated
•When the function terminates
−That memory space is then deallocated
Start here Page 79
−That memory space is then deallocated
•Every (recursive) call has its own set of parameters and (automatic) local
variables

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

Efficiency
•Overhead associated with executing a (recursive) function in terms of
−Memory space
−Computer time
•A recursive function executes more slowly than its iterative counterpart

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

Efficiency (continued)
•On slower computers, especially those with limited memory space
−The slow execution of a recursive function would be visible
•Today’s computers are fast and have inexpensive memory
−Execution of a recursion function is not noticeable

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

Efficiency (continued)
•The choice between the two alternatives depends on the nature of the problem
•For problems such as mission control systems
−Efficiency is absolutely critical and dictates the solution method

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

Efficiency (continued)
•An iterative solution is more obvious and easier to understand than a recursive
solution
•If the definition of a problem is inherently recursive
−Consider a recursive solution

Start here Page 80


Start here Page 81
Start here Page 82
Start here Page 83
Start here Page 84

Вам также может понравиться