CPP Tutorial0
CPP Tutorial0
void main()
{
cout << "My first C++ program." << endl;
getch();
}
Sample Run:
My first C++ program.
• Algorithm:
− Get length of the rectangle
− Get width of the rectangle
− Find the perimeter using the following
equation:
perimeter = 2 * (length + width)
− Multiple line
/*
You can include comments that can
occupy several lines.
*/
• Special symbols
+ ?
- ,
* <=
/ !=
. ==
; >=
• Examples:
-6728
0
78
+763
• Positive integers do not need a + sign
• No commas are used within an integer
− Commas are used for separating items in a list
• bool type
− Two values: true and false
− Manipulate logical (Boolean) expressions
• true and false are called logical values
• bool, true, and false are reserved words
• Mixed expression:
− Has operands of different data types
− Contains integers and floating-point
• Examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
• Evaluation rules:
− If operator has same types of operands
• Evaluated according to the type of the operands
− If operator has both types of operands
• Integer is changed to floating-point
• Operator is evaluated
• Result is floating-point
− Entire expression is evaluated according to
precedence rules
• For example:
#include <iostream>
y = w + x; //Line 4: error
• Named Constant
const double CENTIMETERS_PER_INCH = 2.54;
const int INCHES_PER_FOOT = 12;
The numbers you entered are 15 for feet and 7 for inches.
The total number of inches = 187
The number of centimeters = 474.98
Chapter 3: Input/Output
Objectives
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 100
cin and the Extraction Operator
>> (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 101
Using Predefined Functions in a
Program
• Function (subprogram): set of instructions
− When activated, it accomplishes a task
• main executes when a program is run
• Other functions execute only when called
• C++ includes a wealth of functions
− Predefined functions are organized as a
collection of libraries called header files
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 103
Using Predefined Functions in a
Program (continued)
• Header file may contain several functions
• To use a predefined function, you need the
name of the appropriate header file
− You also need to know:
• Function name
• Number of parameters required
• Type of each parameter
• What the function is going to do
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 104
Using Predefined Functions in a
Program (continued)
• To use pow (power), include cmath
− Syntax: pow(x,y) = xy
• x and y are the arguments or parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 105
Using Predefined Functions in a
Program (continued)
Sample Run:
Line 1: 2 to the power of 6 = 64
Line 4: 12.5 to the power of 3 = 1953.13
Line 5: Square root of 24 = 4.89898
Line 7: u = 181.019
Line 9: Length of str = 20
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 107
cin and the get Function
varChar
− Is a char variable
− Is the argument (parameter) of the function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 108
cin and the ignore Function
• putback function
− Places previous character extracted by the
get function from an input stream back to that
stream
• peek function
− Returns next character from the input stream
− Does not remove the character from that
stream
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 110
putback and peek Functions
(continued)
• The syntax for putback:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 111
The Dot Notation Between I/O
Stream Variables and I/O Functions
• In the statement
cin.get(ch);
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 112
Input Failure
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 113
The clear Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 114
Output and Formatting Output
• Expression is evaluated
• Value is printed
• Manipulator is used to format the output
− Example: endl
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 115
setprecision Manipulator
• Syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 116
fixed Manipulator
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 117
showpoint Manipulator
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 118
setw
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 120
setfill Manipulator
• Example:
− cout << setfill('#');
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 121
left and right Manipulators
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 122
Types of Manipulators
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 123
Input/Output and the string
Type
• An input stream variable (cin) and >>
operator can read a string into a variable of
the data type string
• Extraction operator
− Skips any leading whitespace characters and
reading stops at a whitespace character
• The function getline
− Reads until end of the current line
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 124
File Input/Output
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 125
Programming Example: Movie
Ticket Sale and Donation to Charity
• A theater owner agrees to donate a portion of
gross ticket sales to a charity
• The program will prompt the user to input:
− Movie name
− Adult ticket price
− Child ticket price
− Number of adult tickets sold
− Number of child tickets sold
− Percentage of gross amount to be donated
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 126
Programming Example: I/O
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 127
Programming Example: Problem
Analysis
• The program needs to:
1. Get the movie name
2. Get the price of an adult ticket price
3. Get the price of a child ticket price
4. Get the number of adult tickets sold
5. Get the number of child tickets sold
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 128
Programming Example: Problem
Analysis (continued)
6. Calculate the gross amount
grossAmount = adultTicketPrice *
noOfAdultTicketsSold + childTicketPrice *
noOfChildTicketsSold;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 129
Programming Example: Variables
string movieName;
double adultTicketPrice;
double childTicketPrice;
int noOfAdultTicketsSold;
int noOfChildTicketsSold;
double percentDonation;
double grossAmount;
double amountDonated;
double netSaleAmount;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 130
Programming Example:
Formatting Output
• First column is left-justified
− When printing a value in the first column, use
left
• Numbers in second column are right-justified
− Before printing a value in the second column,
use right
• Use setfill to fill the empty space between
the first and second columns with dots
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 131
Programming Example:
Formatting Output (continued)
• In the lines showing gross amount, amount
donated, and net sale amount
− Use blanks to fill space between the $ sign
and the number
• Before printing the dollar sign
− Use setfill to set the filling character to
blank
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 132
Programming Example: Main
Algorithm
1. Declare variables
2. Set the output of the floating-point to:
− Two decimal places
− Fixed
− Decimal point and trailing zeros
3. Prompt the user to enter a movie name
4. Input movie name using getline because
it might contain spaces
5. Prompt user for price of an adult ticket
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 133
Programming Example: Main
Algorithm (continued)
6. Input price of an adult ticket
7. Prompt user for price of a child ticket
8. Input price of a child ticket
9. Prompt user for the number of adult tickets
sold
10. Input number of adult tickets sold
11. Prompt user for number of child tickets sold
12. Input the number of child tickets sold
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 134
Programming Example: Main
Algorithm (continued)
13. Prompt user for percentage of the gross
amount donated
14. Input percentage of the gross amount
donated
15. Calculate the gross amount
16. Calculate the amount donated
17. Calculate the net sale amount
18. Output the results
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 135
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 137
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 138
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 141
Control Structures (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 142
Relational Operators
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 143
Relational Operators (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 144
Relational Operators and Simple
Data Types
• You can use the relational operators with all
three simple data types:
− 8 < 15 evaluates to true
− 6 != 6 evaluates to false
− 2.5 > 5.8 evaluates to false
− 5.9 <= 7.5 evaluates to true
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 145
Comparing Characters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 146
Relational Operators and the
string Type
• Relational operators can be applied to strings
• Strings are compared character by character,
starting with the first character
• Comparison continues until either a mismatch
is found or all characters are found equal
• If two strings of different lengths are compared
and the comparison is equal to the last
character of the shorter string
− The shorter string is less than the larger string
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 147
Relational Operators and the
string Type (continued)
• Suppose we have the following declarations:
string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str4 = "Big";
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 148
Relational Operators and the
string Type (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 149
Relational Operators and the
string Type (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 150
Relational Operators and the
string Type (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 151
Logical (Boolean) Operators and
Logical Expressions
• Logical (Boolean) operators enable you to
combine logical expressions
unary
binary
binary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 152
Logical (Boolean) Operators and
Logical Expressions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 153
Order of Precedence
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 156
Order of Precedence (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 157
Order of Precedence (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 158
Order of Precedence (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 159
Order of Precedence (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 160
Short-Circuit Evaluation
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 161
int Data Type and Logical
(Boolean) Expressions
• Earlier versions of C++ did not provide built-in
data types that had Boolean values
• Logical expressions evaluate to either 1 or 0
− The value of a logical expression was stored
in a variable of the data type int
• You can use the int data type to manipulate
logical (Boolean) expressions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 162
The bool Data Type and Logical
(Boolean) Expressions
• The data type bool has logical (Boolean)
values true and false
• bool, true, and false are reserved words
• The identifier true has the value 1
• The identifier false has the value 0
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 163
Logical (Boolean) Expressions
• One-Way Selection
• Two-Way Selection
• Compound (Block of) Statements
• Multiple Selections: Nested if
• Comparing if...else Statements with a
Series of if Statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 165
Selection: if and if...else
(continued)
• Using Pseudocode to Develop, Test, and
Debug a Program
• Input Failure and the if Statement
• Confusion Between the Equality Operator
(==) and the Assignment Operator (=)
• Conditional Operator (?:)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 166
One-Way Selection
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 167
One-Way Selection (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 168
One-Way Selection (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 169
One-Way Selection (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 171
Two-Way Selection
• Two-way selection takes the form:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 173
Two-Way Selection (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 174
Two-Way Selection (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 175
Compound (Block of) Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 176
Compound (Block of) Statement
(continued)
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;
}
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 177
Multiple Selections: Nested if
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 178
Multiple Selections: Nested if
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 180
Comparing if…else Statements
with a Series of if Statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 181
Using Pseudocode to Develop,
Test, and Debug a Program
• Pseudocode (pseudo): provides a useful
means to outline and refine a program before
putting it into formal C++ code
• You must first develop a program using paper
and pencil
• On paper, it is easier to spot errors and
improve the program
− Especially with large programs
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 182
Input Failure and the if Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 183
Confusion Between == and =
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 184
Conditional Operator (?:)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 185
switch Structures
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 186
switch Structures (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 188
Terminating a Program with the
assert Function
• Certain types of errors that are very difficult to
catch can occur in a program
− Example: division by zero can be difficult to
catch using any of the programming
techniques examined so far
• The predefined function, assert, is useful in
stopping program execution when certain
elusive errors occur
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 190
The assert Function (continued)
• Syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 192
Programming Example: Cable
Company Billing
• This programming example calculates a
customer’s bill for a local cable company
• There are two types of customers:
− Residential
− Business
• Two rates for calculating a cable bill:
− One for residential customers
− One for business customers
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 193
Programming Example: Rates
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 195
Programming Example: Input and
Output
• Input:
− Customer account number
− Customer code
− Number of premium channels
− For business customers, number of basic
service connections
• Output:
− Customer’s account number
− Billing amount
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 196
Programming Example: Program
Analysis
• Purpose: calculate and print billing amount
• Calculating billing amount requires:
− Customer for whom the billing amount is
calculated (residential or business)
− Number of premium channels to which the
customer subscribes
• For a business customer, you need:
− Number of basic service connections
− Number of premium channels
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 197
Programming Example: Program
Analysis (continued)
• Data needed to calculate the bill, such as bill
processing fees and the cost of a premium
channel, are known quantities
• The program should print the billing amount
to two decimal places
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 198
Programming Example: Algorithm
Design
• Set precision to two decimal places
• Prompt user for account number and
customer type
• If customer type is R or r
− Prompt user for number of premium channels
− Compute and print the bill
• If customer type is B or b
− Prompt user for number of basic service
connections and number of premium channels
− Compute and print the bill
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 199
Programming Example: Variables
and Named Constants
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 200
Programming Example: Formulas
amountDue = RES_BILL_PROC_FEES +
RES_BASIC_SERV_COST
+ numOfPremChannels *
RES_COST_PREM_CHANNEL;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 201
Programming Example: Formulas
(continued)
Billing for business customers:
if (numOfBasicServConn <= 10)
amountDue = BUS_BILL_PROC_FEES +
BUS_BASIC_SERV_COST
+ numOfPremChannels *
BUS_COST_PREM_CHANNEL;
else
amountDue = BUS_BILL_PROC_FEES +
BUS_BASIC_SERV_COST
+ (numOfBasicServConn - 10)
* BUS_BASIC_CONN_COST
+ numOfPremChannels *
BUS_COST_PREM_CHANNEL;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 202
Programming Example: Main
Algorithm
1. Output floating-point numbers in fixed
decimal with decimal point and trailing zeros
• Output floating-point numbers with two
decimal places and set the precision to two
decimal places
2. Prompt user to enter account number
3. Get customer account number
4. Prompt user to enter customer code
5. Get customer code
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 203
Programming Example: Main
Algorithm (continued)
6. If the customer code is r or R,
− Prompt user to enter number of premium
channels
− Get the number of premium channels
− Calculate the billing amount
− Print account number and billing amount
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 204
Programming Example: Main
Algorithm (continued)
7. If customer code is b or B,
− Prompt user to enter number of basic service
connections
− Get number of basic service connections
− Prompt user to enter number of premium
channels
− Get number of premium channels
− Calculate billing amount
− Print account number and billing amount
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 205
Programming Example: Main
Algorithm (continued)
8. If customer code is other than r, R, b, or B,
output an error message
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 206
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 207
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 209
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 211
Why Is Repetition Needed?
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 214
while Looping (Repetition)
Structure (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 215
Designing while Loops
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 216
Case 1: Counter-Controlled
while Loops
• If you know exactly how many pieces of data
need to be read, the while loop becomes a
counter-controlled loop
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 217
Case 2: Sentinel-Controlled
while Loops
• Sentinel variable is tested in the condition
and loop ends when sentinel is encountered
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 218
Telephone Digits
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 219
Case 3: Flag-Controlled while
Loops
• A flag-controlled while loop uses a bool
variable to control the loop
• The flag-controlled while loop takes the
form:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 220
Number Guessing Game
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 222
eof Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 224
Programming Example: Checking
Account Balance
• A local bank in your town needs a program to
calculate a customer’s checking account
balance at the end of each month
• Data are stored in a file in the following form:
467343 23750.40
W 250.00
D 1200
W 75.00
I 120.74
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 225
Programming Example: Checking
Account Balance (continued)
• The first line of data shows the account
number followed by the account balance at
the beginning of the month
• Thereafter each line has two entries:
− Transaction code
− Transaction amount
• Transaction codes
− W or w means withdrawal
− D or d means deposit
− I or i means interest paid by the bank
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 226
Programming Example: Checking
Account Balance (continued)
• Program updates balance after each
transaction
• During the month, if at any time the balance
goes below $1000.00, a $25.00 service fee is
charged
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 227
Programming Example: Checking
Account Balance (continued)
• Program prints the following information:
− Account number
− Balance at the beginning of the month
− Balance at the end of the month
− Interest paid by the bank
− Total amount of deposit
− Number of deposits
− Total amount of withdrawal
− Number of withdrawals
− Service charge if any
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 228
Programming Example: Input and
Output
• Input: file consisting of data in the previous
format
• Output is of the following form:
Account Number: 467343
Beginning Balance: $23750.40
Ending Balance: $24611.49
Interest Paid: $366.24
Amount Deposited: $2230.50
Number of Deposits: 3
Amount Withdrawn: $1735.65
Number of Withdrawals: 6
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 229
Programming Example: Program
Analysis
• The first entry in the input file is the account
number and the beginning balance
• Program first reads account number and
beginning balance
• Thereafter, each entry in the file is of the
following form:
transactionCode transactionAmount
• To determine account balance, process each
entry that contains transaction code and
transaction amount
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 230
Programming Example: Program
Analysis (continued)
• Begin with starting balance and then update
account balance after processing each entry
• If transaction code is D, d, I, or i, transaction
amount is added to the account balance
• If the transaction code is W or w, transaction
amount is subtracted from the balance
• Keep separate counts of withdrawals and
deposits
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 231
Programming Example: Analysis
Algorithm
• Algorithm:
− Declare the variables
− Initialize the variables
− Get the account number and beginning
balance
− Get transaction code and transaction amount
− Analyze transaction code and update the
appropriate variables
− Repeat Steps 4 and 5 for all data
− Print the result
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 232
Programming Example: Variables
and Constants
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 233
Programming Example: Steps
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 234
Programming Example: Steps
(continued)
• Get account number and starting balance
infile >> acctNumber >> beginningBalance;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 235
Programming Example: Steps
(continued)
• Repeat Steps 4 and 5 until there is no more
data
− Since the number of entries in the input file is
not known, use an EOF-controlled while loop
• Print the result
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 236
Programming Example: Main
Algorithm
• Declare and initialize variables
• Open input file
• If input file does not exist, exit
• Open output file
• Output numbers in appropriate formats
• Read accountNumber and
beginningBalance
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 237
Programming Example: Main
Algorithm (continued)
• Set accountBalance to beginningBalance
• Read transactionCode and
transactionAmount
while (not end of input file)
if transactionCode is 'D' or 'd'
Add transactionAmount to accountBalance
Increment numberOfDeposits
if transactionCode is 'I' or 'i'
Add transactionAmount to accountBalance
Add transactionAmount to interestPaid
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 238
Programming Example: Main
Algorithm (continued)
if transactionCode is 'W' or 'w'
Subtract transactionAmount from
accountBalance
Increment numberOfWithdrawals
if (accountBalance < MINIMUM_BALANCE
&& !isServicedCharged)
Subtract SERVICE_CHARGE from accountBalance
Set isServiceCharged to true
if transactionCode is other than 'D', 'd', 'I',
'i', 'W', or 'w', output an error message
• Output the results
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 239
for Looping (Repetition)
Structure
• The general form of the for statement is:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 241
for Looping (Repetition)
Structure (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 242
for Looping (Repetition)
Structure (continued)
• C++ allows you to use fractional values for
loop control variables of the double type
− Results may differ
• The following is a semantic error:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 244
do…while Looping (Repetition)
Structure
• General form of a do...while:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 246
do…while Looping (Repetition)
Structure (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 247
Divisibility Test by 3 and 9
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 249
Choosing the Right Looping
Structure
• All three loops have their place in C++
− If you know or can determine in advance the
number of repetitions needed, the for loop is
the correct choice
− If you do not know and cannot determine in
advance the number of repetitions needed,
and it could be zero, use a while loop
− If you do not know and cannot determine in
advance the number of repetitions needed,
and it is at least one, use a do...while loop
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 250
break and continue Statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 251
break & continue Statements
(continued)
• continue is used in while, for, and
do…while structures
• When executed in a loop
− It skips remaining statements and proceeds
with the next iteration of the loop
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 252
Nested Control Structures
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 253
Nested Control Structures
(continued)
• What is the result if we replace the first for
statement with the following?
for (i = 5; i >= 1; i--)
• Answer:
*****
****
***
**
*
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 254
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 255
Summary (continued)
• while: expression is the decision maker, and
the statement is the body of the loop
• A while loop can be:
− Counter-controlled
− Sentinel-controlled
− EOF-controlled
• In the Windows console environment, the
end-of-file marker is entered using Ctrl+z
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 256
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 257
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 259
Introduction
• Functions are like building blocks
• They allow complicated programs to be
divided into manageable pieces
• Some advantages of functions:
− 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
− Can be re-used (even in different programs)
− Enhance program readability
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 260
Introduction (continued)
• Functions
− Called modules
− Like miniature programs
− Can be put together to form a larger program
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 261
Predefined Functions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 262
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 263
Predefined Functions (continued)
• pow(x,y) calculates xy
− pow(2, 3) = 8.0
− Returns a value of type double
− x and y are the parameters (or arguments)
• The function has two parameters
• sqrt(x) calculates the nonnegative square
root of x, for x >= 0.0
− sqrt(2.25) is 1.5
− Type double
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 264
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 265
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 266
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 267
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 269
User-Defined Functions
• Value-returning functions: have a return type
− Return a value of a specific data type using
the return statement
• Void functions: do not have a return type
− Do not use a return statement to return a
value
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 270
Value-Returning Functions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 271
Value-Returning Functions
(continued)
• Because the value returned by a value-
returning function is unique, we must:
− Save the value for further calculation
− Use the value in some calculation
− Print the value
• A value-returning function is used in an
assignment or in an output statement
• One more thing is associated with functions:
− The code required to accomplish the task
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 272
Value-Returning Functions
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 273
Value-Returning Functions
(continued)
• Heading: first four properties above
− Example: int abs(int number)
• Formal Parameter: variable declared in the
heading
− Example: number
• Actual Parameter: variable or expression
listed in a call to a function
− Example: x = pow(u, v)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 274
Syntax: Value-Returning Function
• Syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 275
Syntax: Formal Parameter List
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 276
Function Call
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 277
Syntax: Actual Parameter List
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 278
return Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 279
Syntax: return Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 280
Function Prototype
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 282
Function Prototype (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 284
Palindrome Number
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 285
Palindrome Number (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 286
Flow of Execution
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 288
Programming Example: Largest
Number
• The function larger is used to determine the
largest number from a set of numbers
• Program determines the largest number from
a set of 10 numbers
• Input: a set of 10 numbers
• Output: the largest of 10 numbers
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 289
Programming Example: Program
Analysis
• Suppose that the input data is:
15 20 7 8 28 21 43 12 35 3
• Read the first number of the data set
− Because this is the only number read to this
point, you may assume that it is the largest
number so far and call it max
• Read the second number and call it num
− Compare max and num, and store the larger
number into max
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 290
Programming Example: Program
Analysis (continued)
• Now max contains the larger of the first two
numbers
• Read the third number and compare it with
max and store the larger number into max
− max contains the largest of the first three
numbers
• Read the next number, compare it with max,
and store the larger into max
• Repeat this process for each remaining
number in the data set
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 291
Programming Example: Algorithm
Design
• Read the first number
− Because this is the only number that you have
read, it is the largest number so far
− Save it in a variable called max
• For each remaining number in the list
− Read the next number
− Store it in a variable called num
− Compare num and max
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 292
Programming Example: Algorithm
Design (continued)
• For each remaining number in the list
(continued)
− If max < num
• num is the new largest number
• update the value of max by copying num into max
− If max >= num, discard num; that is, do
nothing
• Because max now contains the largest
number, print it
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 293
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 298
Objectives (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 299
Void Functions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 300
Void Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 301
Void Functions without Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 302
Void Functions with Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 303
Void Functions with Parameters
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 304
Void Functions with Parameters
(continued)
• Value parameter: a formal parameter that
receives a copy of the content of
corresponding actual parameter
• Reference parameter: a formal parameter
that receives the location (memory address)
of the corresponding actual parameter
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 305
Value Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 306
Reference Variables as Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 308
Calculate Grade
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 309
Calculate Grade (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 310
Scope of an Identifier
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 319
Scope of an Identifier (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 322
Global Variables, Named
Constants, and Side Effects
• Using global variables has side effects
• A function that uses global variables is not
independent
• 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 in one area of the program
may appear to be from another area
• Global named constants have no side effects
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 323
Static and Automatic Variables
• Automatic variable: memory is allocated at
block entry and deallocated at block exit
− By default, variables declared within a block
are automatic variables
• Static variable: memory remains allocated as
long as the program executes
− Variables declared outside of any block are
static variables
− Declare a static variable within a block by
using the reserved word static
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 324
Static and Automatic Variables
(continued)
• The syntax for declaring a static variable is:
• 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
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 325
Function Overloading: An
Introduction
• In a C++ program, several functions can have
the same name
− This is called function overloading or
overloading a function name
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 326
Function Overloading (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 327
Function Overloading (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 328
Function Overloading (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 329
Function Overloading (continued)
• Syntax error:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 330
Functions with Default Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 331
Functions with Default Parameters
(continued)
• All 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:
− You must omit all of the arguments to its right
• Default values can be constants, global
variables, or function calls
− However, you cannot assign a constant value
as a default value to a reference parameter
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 332
Functions with Default Parameters
(continued)
• Consider the following prototype:
• Assume:
− a, b are int, ch is char, d is double
• Examples of legal calls:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 333
Functions with Default Parameters
(continued)
• Examples of illegal function prototypes with
default parameters:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 334
Programming Example: Classify
Numbers
• In this example, we use functions to rewrite
the program that determines the number of
odds and evens from a given list of integers
• Main algorithm remains the same:
− Initialize variables, zeros, odds, evens to 0
− Read a number
− If number is even, increment the even count
• If number is also zero, increment the zero
count; else increment the odd count
− Repeat Steps 2-3 for each number in the list
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 335
Programming Example: Classify
Numbers (continued)
• The program functions include:
− initialize: initialize the variables, such as
zeros, odds, and evens
− getNumber: get the number
− classifyNumber: determine if number is
odd or even (and whether it is also zero); this
function also increments the appropriate count
− printResults: print the results
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 336
Programming Example: Main
Algorithm
• Call initialize to initialize variables
• Prompt the user to enter 20 numbers
• For each number in the list
− Call getNumber to read a number
− Output the number
− Call classifyNumber to classify the number
and increment the appropriate count
• Call printResults to print the final results
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 338
Summary
• Void function: does not have a data type
− A return statement without any value can be
used in a void function to exit it early
− The heading starts with the word void
− To call the function, you use the function name
together with the actual parameters in a stand-
alone statement
• Two types of formal parameters:
− Value parameters
− Reference parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 340
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 341
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 345
Enumeration Type (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 347
Enumeration Type (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 348
Declaring Variables
• Syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 350
Assignment
• The statement:
popularSport = FOOTBALL;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 351
Operations on Enumeration Types
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 352
Relational Operators
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 353
Input /Output of Enumeration
Types
• I/O are defined only for built-in data types
− Enumeration type cannot be input/output
(directly)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 354
Functions and Enumeration Types
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 355
Declaring Variables When
Defining the Enumeration Type
• You can declare variables of an enumeration
type when you define an enumeration type:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 356
Anonymous Data Types
• Anonymous type : values are directly
specified in the declaration, with no type name
• Drawbacks:
− Cannot pass/return an anonymous type to/from
a function
− Values used in one type can be used in
another, but are treated differently:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 357
typedef Statement
• You can create synonyms or aliases to a data
type using the typedef statement
• Syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 358
Namespaces
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 359
Namespaces (continued)
• Global identifiers in a header file used in a
program become global in the program
− Syntax error occurs if an identifier in a
program has the same name as a global
identifier in the header file
• Same problem can occur with third-party
libraries
− Common solution: third-party vendors begin
their global identifiers with _ (underscore)
• Do not begin identifiers in your program with _
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 360
Namespaces (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 361
Namespaces (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 362
Namespaces (continued)
• The scope of a namespace member is local
to the namespace
• Ways a namespace member can be
accessed outside the namespace:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 363
Accessing a namespace Member
• Examples:
globalType::RATE
globalType::printResult();
• After the using statement, it is not necessary
to precede the namespace_name:: before
the namespace member
− Unless a namespace member and a global
identifier or a block identifier have same name
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 364
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', is in position 0
− The second character, 'i', is in position 1
− name is capable of storing any size string
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 365
string Type (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 366
Additional string Operations
• length
• size
• find
• substr
• swap
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 367
length Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 368
size Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 370
find Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 371
find Function (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 372
substr Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 373
substr Function (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 374
swap Function
• Interchanges contents of two string variables
• Syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 376
Programming Example: Pig Latin
Strings (continued)
• Rules (continued):
− If the string does not begin with a vowel, first
add "-" at the end of the string
• Then move the first character of the string to the
end of the string until the first character of the
string becomes a vowel
• Next, add the string "ay" at the end
• Example: pig Latin form of "There" is "ere-
Thay"
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 377
Programming Example: Pig Latin
Strings (continued)
• Rules (continued):
− Strings such as "by" contain no vowels
• The letter 'y' can be considered a vowel
• For this program the vowels are a, e, i, o, u, y, A,
E, I, O, U, and Y
− Strings such as "1234" contain no vowels
• The pig Latin form of a string that has no vowels
in it is the string followed by the string "-way"
• Example: pig Latin form of "1234" is "1234-
way"
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 378
Programming Example: Problem
Analysis
• If str denotes a string:
− Check the first character, str[0], of str
− If it is a vowel, add "-way" at the end of str
− If it is not a vowel:
• First add "-" at the end of the string
• Remove the first character of str from str and
put it at end of str
• Now the second character of str becomes the
first character of str
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 379
Programming Example: Problem
Analysis (continued)
• If str denotes a string (continued):
− This process is repeated until either
• The first character of str is a vowel
• All characters of str are processed, in which
case str does not contain any vowels
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 380
Programming Example: Algorithm
Design
• The program contains the following functions:
− isVowel determines if a character is a vowel
− rotate moves first character of str to the
end of str
− pigLatinString finds pig Latin form of str
• Steps in the algorithm:
− Get str
− Use pigLatinString to find the pig Latin
form of str
− Output the pig Latin form of str
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 381
Programming Example: Function
isVowel
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 382
Programming Example: Function
rotate
• Takes a string as a parameter
• Removes the first character of the string
− Places it at end of the string by extracting the
substring starting at position 1 until the end of
the string, then adding the first character of the
string
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 383
Programming Example: Function
pigLatinString
• If pStr[0] is a vowel, add "-way" at end
• If pStr[0] is not a vowel:
− Move first character of pStr to the end of pStr
− The second character of pStr becomes the first
character of pStr
• Now pStr may or may not contain a vowel
− Use a bool variable, foundVowel, which is set to
true if pStr contains a vowel and false
otherwise
− Initialize foundVowel to false
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 384
Programming Example: Function
pigLatinString (continued)
− If pStr[0] is not a vowel, move str[0] to
the end of pStr by calling the function
rotate
− Repeat third step until either the first character
of pStr becomes a vowel or all characters of
pStr have been checked
• Convert pStr into the pig Latin form
• Return pStr
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 385
Programming Example: Main
Algorithm
• Get the string
• Call pigLatinString to find the pig Latin
form of the string
• Output the pig Latin form of the string
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 386
Summary
• Enumeration type: set of ordered values
− Created with reserved word enum creates an
enumeration type
• No arithmetic operations are allowed on the
enumeration type
• Relational operators can be used with enum
values
• Enumeration type values cannot be input or
output directly
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 387
Summary (continued)
• Anonymous type: a variable’s values are
specified without any type name
• Reserved word typedef creates synonyms
or aliases to previously defined data types
• The namespace mechanism is a feature of
ANSI/ISO Standard C++
• A namespace member is usually a named
constant, variable, function, or another
namespace
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 388
Summary (continued)
• Keyword namespace must appear in the
using statement
• A string is a sequence of zero or more
characters
• Strings in C++ are enclosed in ""
• In C++, [] is the array subscript operator
• The function length returns the number of
characters currently in the string
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 389
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 390
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 393
Data Types
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 394
Arrays
• Array: a collection of a fixed number of
components wherein all of the components
have the same data type
• In a one-dimensional array, the components
are arranged in a list form
• Syntax for declaring a one-dimensional array:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 395
Arrays (continued)
• Example:
int num[5];
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 396
Accessing Array Components
• General syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 397
Accessing Array Components
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 398
Accessing Array Components
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 399
Accessing Array Components
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 400
Accessing Array Components
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 401
Processing One-Dimensional Arrays
• Some basic operations performed on a one-
dimensional array are:
− Initializing
− Inputting data
− Outputting data stored in an array
− Finding the largest and/or smallest element
• Each operation requires ability to step through
the elements of the array
• Easily accomplished by a loop
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 402
Processing One-Dimensional Arrays
(continued)
• Consider the declaration
int list[100]; //array of size 100
int i;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 403
Array Index Out of Bounds
• If we have the statements:
double num[10];
int i;
• The component num[i] is valid 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 <= ARRAY_SIZE-1
− Otherwise, we say the index is out of bounds
• In C++, there is no guard against indices that
are out of bounds
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 405
Array Initialization During
Declaration
• Arrays can be initialized during declaration
− In this case, it is not necessary to specify the size
of the array
• Size determined by the number of initial values in the
braces
• Example:
double sales[] = {12.25, 32.50, 16.90, 23, 45.68};
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 406
Partial Initialization of Arrays
During Declaration
• The statement:
int list[10] = {0};
declares list to be an array of 10 components
and initializes all of them 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
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 407
Partial Initialization of Arrays
During Declaration (continued)
• The statement:
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 an array of 25 components; initializes
list[0] to 4 and list[1] to 7; all other
components are initialized to 0
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 408
Some Restrictions on Array
Processing
• Consider the following statements:
• Solution:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 409
Some Restrictions on Array
Processing (continued)
• The following is illegal too:
• Solution:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 410
Arrays as Parameters to Functions
• Arrays are passed by reference only
• The symbol & is not used when declaring an
array as a formal parameter
• The size of the array is usually omitted
− If provided, it is ignored by the compiler
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 411
Constant Arrays as Formal
Parameters
• Recall that when a formal parameter is a
reference parameter, then whenever the
formal parameter changes, the actual
parameter changes as well. However, even
though an array is always passed by
reference, you can still prevent the function
from changing the actual parameter. You do
so by using the reserved word const in the
declaration of the formal parameter.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 412
Constant Arrays as Formal
Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 414
Constant Arrays as Formal
Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 415
Base Address of an Array and
Array in Computer Memory
• The base address of an array is the address, or
memory location of the first array component
• If list is a one-dimensional array, its base
address is the address of list[0]
• When we pass an array as a parameter, the
base address of the actual array is passed to
the formal parameter
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 416
• Now myList is the name of an array. There is
also a memory space associated with the
identifier myList, and the base address of the
array is stored in that memory space.
• Consider the following statement:
cout << myList << endl;
• Earlier, we said that this statement will not give
the desired result. That is, this statement will not
output the values of the components of myList.
In fact, the statement outputs the value of
myList, which is the base address of the array.
This is why the statement will not generate a
syntax error.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 418
• the expression myList<=yourList evaluates
to true if the base address of the array myList
is less than the base address of the array
yourList; and evaluates to false otherwise.
• It does not determine whether the elements of
myList are less than or equal to the
corresponding elements of yourList.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 419
• When you pass an array as a parameter, the
base address of the actual array is passed to
the formal parameter. For example, suppose
that you have the following function:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 420
Base Address of an Array and
Array in Computer Memory
• Also, suppose that you have the following call
to this function:
arrayAsParameter(myList, 5);
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 422
Integral Data Type and Array
Indices
• C++ allows any integral type to be used as an
array index
• Example:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 423
Other Ways to Declare Arrays
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 424
C-Strings (Character Arrays)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 425
C-Strings (Character Arrays)
(continued)
• Consider the statement
char name[16];
• Since C-strings are null terminated and name
has 16 components, the largest string that it
can store has 15 characters
• If you store a string of length, say 10 in name
− The first 11 components of name are used
and the last five are left unused
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 426
C-Strings (Character Arrays)
(continued)
• The statement
char name[16] = "John";
declares an array name of length 16 and
stores the C-string "John" in it
• The statement
char name[] = "John";
declares an array name of length 5 and stores
the C-string "John" in it
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 427
C-Strings (Character Arrays)
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 428
String Comparison
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 429
Reading and Writing Strings
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 431
String Input
• cin >> name; stores the next input C-
string into name
• To read strings with blanks, use get:
cin.get(str, m+1);
− Stores the next m characters into str but the
newline character is not stored in str
− If the input string has fewer than m
characters, the reading stops at the newline
character
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 432
String Output
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 433
Specifying Input/Output Files at
Execution Time
• You can let the user specify the name of the
input and/or output file at execution time:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 434
string Type and Input/Output
Files
• Argument to the function open must be a
null-terminated string (a C-string)
• If we use a variable of type string to read
the name of an I/O file, the value must first be
converted to a C-string before calling open
• Syntax:
strVar.c_str()
where strVar is a variable of type string
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 435
Parallel Arrays
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 436
Two-Dimensional Arrays
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 438
Accessing Array Components
• Syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 439
Accessing Array Components
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 440
Two-Dimensional Array
Initialization During Declaration
• Two-dimensional arrays can be initialized
when they are declared:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 441
Two-Dimensional Arrays and
Enumeration Types
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 442
Processing Two-Dimensional
Arrays
• Ways to process a two-dimensional array:
− Process the entire array
− Process a particular row of the array, called
row processing
− 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
− To process, use algorithms similar to
processing one-dimensional arrays
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 443
Processing Two-Dimensional
Arrays (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 444
Initialization
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 445
Print
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 446
Input
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 447
Sum by Row
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 448
Sum by Column
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 449
Largest Element in Each Row and
Each Column
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 450
Reversing Diagonal
• Before:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 451
Reversing Diagonal (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 452
Reversing Diagonal (continued)
• After:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 453
Passing Two-Dimensional Arrays as
Parameters to Functions
• Two-dimensional arrays can be passed as
parameters to a function
− Pass by reference
• Base address (address of first component of the
actual parameter) is passed to formal parameter
• Two-dimensional arrays are stored in row
order
• When declaring a two-dimensional array as a
formal parameter, can omit size of first
dimension, but not the second
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 454
Arrays of Strings
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 455
Arrays of Strings and the string
Type
• To declare an array of 100 components of
type string:
string list[100];
• Basic operations, such as assignment,
comparison, and input/output, can be
performed on values of the string type
• The data in list can be processed just like
any one-dimensional array
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 456
Arrays of Strings and C-Strings
(Character Arrays)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 457
Another Way to Declare a Two-
Dimensional Array
• Consider the following:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 458
Multidimensional Arrays
• To access a component:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 459
Multidimensional Arrays (continued)
• When declaring a multidimensional array as a
formal parameter in a function
− Can omit size of first dimension but not other
dimensions
• As parameters, multidimensional arrays are
passed by reference only
• A function cannot return a value of the type
array
• There is no check if the array indices are within
bounds
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 460
Programming Example: Code
Detection
• When a message is transmitted in secret code
over a transmission channel, it is usually
transmitted as a sequence of bits (0s and 1s)
• Due to noise in the transmission channel, the
transmitted message may become corrupted
− Message received at destination is not the
same as the message transmitted
− Some of the bits may have been changed
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 461
Programming Example: Code
Detection (continued)
• Several techniques to check the validity of the
transmitted message at the destination
• One technique is to transmit the same
message twice
− At the destination, both copies of the message
are compared bit by bit
− If the corresponding bits are the same, the
message received is error-free
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 462
Programming Example: Code
Detection (continued)
• We write a program to check if the message
received at the destination is error-free
• For simplicity, assume that:
− The secret code representing the message is
a sequence of digits (0 to 9)
− The maximum length of the message is 250
digits
• The first number in the message is the length
of the message
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 463
Programming Example: Code
Detection (continued)
• If the secret code is
7 9 2 7 8 3 5 6
then the message is seven digits long
• The above message is transmitted (twice) as
7 9 2 7 8 3 5 6 7 9 2 7 8 3 5 6
• Input: a file containing the secret code and its
copy
• Output: the secret code, its copy, and a
message if the received code is error-free
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 464
Programming Example: Code
Detection (continued)
• The results are output in the following form:
Code Digit Code Digit Copy
9 9
2 2
7 7
8 8
3 3
5 5
6 6
• Message transmitted OK
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 465
Programming Example: Problem
Analysis
• Because we have to compare digits of the
secret code and its copy:
− First, read the secret code and store it in an
array
− Next, read first digit of the copy and compare it
with the first digit of the code, and so on
− If any corresponding digits are not the same,
print a message next to the digits
• The first number in the secret code, and in
the copy, indicates the length of the code
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 466
Programming Example: Algorithm
Design
• Open the input and output files
• If the input file does not exist, exit the
program
• Read the length of the secret code
• If the length of the secret code is greater than
250, terminate the program because the
maximum length of the code in this program
is 250
• Read and store the secret code into an array
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 467
Programming Example: Algorithm
Design (continued)
• Read the length of the copy
• If the length of the secret code and its copy
are the same, compare the codes; otherwise,
print an error message
• Note: To simplify function main, write a
function, readCode, to read the secret code
and another function, compareCode, to
compare the codes
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 468
Programming Example:
readCode
• First, read length of secret code
• If length of secret code is greater than 250
− Set lenCodeOk (a reference parameter) to
false and the function terminates
• Value of lenCodeOk is passed to calling
function to indicate if secret code was read
successfully
• If length of code is less than 250, readCode
reads and stores secret code into an array
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 469
Programming Example:
readCode (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 470
Programming Example:
compareCode
• Set a bool variable codeOk to true
• If length of code and copy are not equal
− Output error message and terminate function
• For each digit in input file
− Read the next digit of secret code copy
− Output digits from code and copy
− If corresponding digits are not equal, output
error message and set codeOk to false
• If codeOk, output message indicating code
transmitted OK, else output an error message
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 471
Programming Example:
compareCode (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 472
Programming Example:
compareCode (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 473
Programming Example: Main
Algorithm
• Declare variables
• Open the files
• Call readCode to read the secret code
• If (length of the secret code <= 250)
− Call compareCode to compare the codes
else
− Output an appropriate error message
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 474
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 475
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 477
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 478
C++ Programming:
From Problem Analysis
to Program Design, Third Edition
Chapter 10: Applications of Arrays
(Searching and Sorting) and the vector
Type
Objectives
In this chapter you will:
• Learn how to implement the sequential
search algorithm
• Explore how to sort an array using the bubble
sort, selection sort, and insertion sort
algorithms
• Learn how to implement the binary search
algorithm
• Become familiar with the vector type
C++ Programming: From Problem Analysis to Program Design, Third Edition 480
List Processing
C++ Programming: From Problem Analysis to Program Design, Third Edition 481
Searching
C++ Programming: From Problem Analysis to Program Design, Third Edition 482
Sequential Search
C++ Programming: From Problem Analysis to Program Design, Third Edition 485
Sorting a List: Selection Sort
C++ Programming: From Problem Analysis to Program Design, Third Edition 490
Sorting a List: Selection Sort
(continued)
• On successive passes, locate the smallest
item in the list starting from the next element
C++ Programming: From Problem Analysis to Program Design, Third Edition 491
Sorting a List: Insertion Sort
The insertion sort algorithm sorts the list by moving each element to its
proper place.
C++ Programming: From Problem Analysis to Program Design, Third Edition 494
Sequential Search on an Ordered
List
• General form of sequential search algorithm
on a sorted list:
C++ Programming: From Problem Analysis to Program Design, Third Edition 500
Binary Search
C++ Programming: From Problem Analysis to Program Design, Third Edition 504
Binary Search (continued)
C++ Programming: From Problem Analysis to Program Design, Third Edition 509
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Third Edition 514
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Third Edition 515
C++ Programming:
From Problem Analysis
to Program Design, Third Edition
Chapter 10: Applications of Arrays
(Searching and Sorting) and the vector
Type
Programming Example
C++ Programming: From Problem Analysis to Program Design, Third Edition 518
Input and Output
• For example, assume the input ” name.txt” file looks
like:
wael
ahmed
ali
mohammed
haithm
C++ Programming: From Problem Analysis to Program Design, Third Edition 519
Input and Output
• For example, assume the input ” course_1.txt” file
looks like:
wael 70
ahmed 75
ali 60
mohammed 55
haithm 40
The first line indicates that wael received 70 marks in
course number 1.
C++ Programming: From Problem Analysis to Program Design, Third Edition 520
Input and Output
• Output consists of election results in tabular form as
described and identifies the winner.
C++ Programming: From Problem Analysis to Program Design, Third Edition 521
Problem Analysis
C++ Programming: From Problem Analysis to Program Design, Third Edition 522
Problem Analysis (continued)
C++ Programming: From Problem Analysis to Program Design, Third Edition 523
Problem Analysis (continued)
C++ Programming: From Problem Analysis to Program Design, Third Edition 524
Algorithm Design
C++ Programming: From Problem Analysis to Program Design, Third Edition 525
Algorithm Design
1. Read candidate names into the array
candidatesName
C++ Programming: From Problem Analysis to Program Design, Third Edition 526
Algorithm Design
2. Sort candidatesName
C++ Programming: From Problem Analysis to Program Design, Third Edition 527
Algorithm Design
3. Initialize votesByRegion and totalVotes
C++ Programming: From Problem Analysis to Program Design, Third Edition 528
Process Voting Data
C++ Programming: From Problem Analysis to Program Design, Third Edition 529
Process Voting Data (continued)
C++ Programming: From Problem Analysis to Program Design, Third Edition 530
Process Voting Data (continued)
C++ Programming: From Problem Analysis to Program Design, Third Edition 531
Function printResults
• Initialize sumVotes, largestVotes, winLoc to 0
• For each row in each array
if (largestVotes < tVotes[i])
{
largestVotes = tVotes[i];
winLoc = i;
}
sumVotes = sumVotes + tVotes[i];
• Output from corresponding rows of arrays
• Output the final lines of output
C++ Programming: From Problem Analysis to Program Design, Third Edition 532
Main Algorithm: Function main
5. Close candDat.txt
C++ Programming: From Problem Analysis to Program Design, Third Edition 533
Main Algorithm: Function main
(continued)
7. Initialize votesByRegion and totalVotes
C++ Programming: From Problem Analysis to Program Design, Third Edition 534
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 537
Design, Fifth Edition
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 538
Design, Fifth Edition
Accessing struct Members
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 539
Design, Fifth Edition
Accessing struct Members
(continued)
• To initialize the members of newStudent:
newStudent.GPA = 0.0;
newStudent.firstName = "John";
newStudent.lastName = "Brown";
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 540
Design, Fifth Edition
Accessing struct Members
(continued)
− More examples:
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 542
Design, Fifth Edition
Assignment
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 543
Design, Fifth Edition
Assignment (continued)
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 544
Design, Fifth Edition
Example:
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 545
Design, Fifth Edition
Comparison (Relational Operators)
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 546
Design, Fifth Edition
Input/Output
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 547
Design, Fifth Edition
struct Variables and Functions
• A struct variable can be passed as a
parameter by value or by reference
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 548
Design, Fifth Edition
Arrays versus structs
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 549
Design, Fifth Edition
Arrays in structs
• Two key items are associated with a list:
− Values (elements)
− Length of the list
• Define a struct containing both items:
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 550
Design, Fifth Edition
Arrays in structs
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 551
Design, Fifth Edition
Arrays in structs(cont'd.)
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 552
552
Design, Fifth Edition
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 553
Design, Fifth Edition
struct in Array
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 554
Design, Fifth Edition
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 555
Design, Fifth Edition
structs within a struct
versus
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 557
Design, Fifth Edition
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 558
Design, Fifth Edition
Programming Example
C++ Programming: From Problem Analysis to Program Design, Second Edition 562
Input/Output
C++ Programming: From Problem Analysis to Program Design, Second Edition 563
Problem Analysis
C++ Programming: From Problem Analysis to Program Design, Second Edition 564
Program Analysis (continued)
C++ Programming: From Problem Analysis to Program Design, Second Edition 565
Program Analysis (continued)
C++ Programming: From Problem Analysis to Program Design, Second Edition 567
Program Analysis (continued)
• For each entry in the file containing the
sales data
1. Read ID, month, sale amount for the month
2. Search salesPersonList to locate the
component corresponding to this
salesperson
3. Determine the quarter corresponding to the
month
4. Update the sales for the quarter by adding
the sale amount for the month
C++ Programming: From Problem Analysis to Program Design, Second Edition 568
Program Analysis (continued)
C++ Programming: From Problem Analysis to Program Design, Second Edition 569
Algorithm Design
• Translates into the following algorithm
1. Initialize the array sales
2. Process the sales data
3. Calculate the total sale by salesman
4. Calculate the total sale by quarter
5. Print the report
6. Calculate and print maximum sale by
salesman
7. Calculate and print maximum sale by quarter
C++ Programming: From Problem Analysis to Program Design, Second Edition 570
Main Algorithm
C++ Programming: From Problem Analysis to Program Design, Second Edition 571
Main Algorithm (continued)
C++ Programming: From Problem Analysis to Program Design, Second Edition 572
Main Algorithm (continued)
C++ Programming: From Problem Analysis to Program Design, Second Edition 573
Main Algorithm (continued)
C++ Programming: From Problem Analysis to Program Design, Second Edition 574
Main Algorithm (continued)
C++ Programming: From Problem Analysis to Program Design, Second Edition 575
Organization of Large Programs
C++ Programming: From Problem Analysis to Program Design, Second Edition 576
Include Files
C++ Programming: From Problem Analysis to Program Design, Second Edition 577
Include File Example
C++ Programming: From Problem Analysis to Program Design, Second Edition 578
System Includes vs. User Includes
C++ Programming: From Problem Analysis to Program Design, Second Edition 579
Summary
Prepared by: Malak Abdullah----C++ Programming: From Problem Analysis to Program 580
Design, Fifth Edition
Summary (continued)