You are on page 1of 287

HIJJAWI TECHNOLOGY ELITE

Outline

Introduction to Programming

Chapter 1:
Introduction to computers and
C++ Programming
Dr. Mohammad A. Alzubaidi

Yarmouk University
Computer Engineering Department

 2003 Prentice Hall, Inc.


All rights reserved.
2

What is a Computer?

• Computer
– Device capable of performing computations and making
logical decisions
• Computer programs
– Sets of instructions that control computer’s processing of
data
• Hardware
– Various devices comprising computer
• Keyboard, screen, mouse, disks, memory, CD-ROM,
processing units, …
• Software
– Programs that run on computer

 2003 Prentice Hall, Inc. All rights reserved.


3
Machine Languages, Assembly Languages,
and High-level Languages
• Three types of computer languages
1. Machine language
• Only language computer directly understands
• “Natural language” of computer
• Defined by hardware design
– Machine-dependent
• Generally consist of strings of numbers
– Ultimately 0s and 1s
• Instruct computers to perform elementary operations
– One at a time
• Cumbersome for humans
• Example:
101001010101001
010100010000010
110010001001001

 2003 Prentice Hall, Inc. All rights reserved.


4
Machine Languages, Assembly Languages,
and High-level Languages
• Three types of computer languages
2. Assembly language
• English-like abbreviations representing elementary computer
operations
• Clearer to humans
• Incomprehensible to computers
– Translator programs (assemblers)
• Convert to machine language
• Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY

 2003 Prentice Hall, Inc. All rights reserved.


5
Machine Languages, Assembly Languages,
and High-level Languages
• Three types of computer languages
3. High-level languages
• Similar to everyday English, use common mathematical
notations
• Single statements accomplish substantial tasks
– Assembly language requires many instructions to
accomplish simple tasks
• Translator programs (compilers)
– Convert to machine language
• Interpreter programs
– Directly execute high-level language programs
• Example:
grossPay = basePay + overTimePay

 2003 Prentice Hall, Inc. All rights reserved.


6

Basics of a Typical C++ Environment


Program is created in
Editor Disk
Phases of C++ Programs: the editor and stored
on disk.

Preprocessor Disk Preprocessor program


1. Edit processes the code.
Compiler creates
Compiler Disk object code and stores
2. Preprocess it on disk.
Linker links the object
Linker Disk code with the libraries,
3. Compile Primary
creates a.out and
stores it on disk
Memory
Loader
4. Link
Loader puts program
in memory.
5. Load Disk ..
..
..

6. Execute CPU
Primary
Memory

CPU takes each


instruction and
executes it, possibly
storing new data
..
.. values as the program
..
executes.
 2003 Prentice Hall, Inc. All rights reserved.
7

A Simple Program: Printing a Line of Text

• Comments
– Document programs
– Improve program readability
– Ignored by compiler
– Single-line comment
• Begin with //
• Preprocessor directives
– Processed by preprocessor before compiling
– Begin with #

 2003 Prentice Hall, Inc. All rights reserved.


8
1 // Fig. 1.2: fig01_02.cpp
2 // A first program in C++. Single-line comments. Outline
3 Function main
#include <iostream> returns an
4 integer { begins Preprocessor
value.
Left brace function directive to
include input/output Statements
stream fig01_02.cpp
5 // function main begins
body. program main appears
execution
Function end with a(1 of 1)
6 int main() header
exactly once file <iostream>.
in every C++ semicolon ;.
7 {
program.. fig01_02.cpp
8 std::cout << "Welcome to C++!\n";
9 Corresponding right brace } output (1 of 1)
10 return 0; // indicate
ends thatbody.
function program ended successfully
11 Name coutStream insertion
belongs to operator.
12 } // end function main namespace std.

Keyword return is one of


Welcome to C++!
several means to exit
function; value 0 indicates
program terminated
successfully.

 2003 Prentice Hall, Inc.


All rights reserved.
9

A Simple Program: Printing a Line of Text

• Standard output stream object


– std::cout
– “Connected” to screen
– <<
• Stream insertion operator
• Value to right (right operand) inserted into output stream
• Namespace
– std:: specifies using name that belongs to “namespace”
std
– std:: removed through use of using statements
• Escape characters
– \
– Indicates “special” character output

 2003 Prentice Hall, Inc. All rights reserved.


10

A Simple Program: Printing a Line of Text

Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.

 2003 Prentice Hall, Inc. All rights reserved.


11
1 // Fig. 1.4: fig01_04.cpp
2 // Printing a line with multiple statements.
Outline
3 #include <iostream>
4
fig01_04.cpp
5 // function main begins program execution Multiple stream insertion
6 int main()
(1 of 1)
statements produce one line
7 {
of output. fig01_04.cpp
8 std::cout << "Welcome ";
9 std::cout << "to C++!\n"; output (1 of 1)
10
11 return 0; // indicate that program ended successfully
12
13 } // end function main

Welcome to C++!

using statements
Eliminate use of std:: prefix
Write cout instead of std::cout

 2003 Prentice Hall, Inc.


All rights reserved.
12
1 // Fig. 1.5: fig01_05.cpp
2 // Printing multiple lines with a single statement
Outline
3 #include <iostream>
4
fig01_05.cpp
5 // function main begins program execution Using newline characters to
6 int main() print on multiple lines. (1 of 1)
7 {
8 std::cout << "Welcome\nto\n\nC++!\n"; fig01_05.cpp
9 output (1 of 1)
10 return 0; // indicate that program ended successfully
11
12 } // end function main

Welcome
to

C++!

 2003 Prentice Hall, Inc.


All rights reserved.
13
Another Simple Program:
Adding Two Integers
• Variables
– Location in memory where value can be stored
– Common data types
• int - integer numbers
• char - characters
• double - floating point numbers
– Declare variables with name and data type before use
int integer1;
int integer2;
int sum;
– Can declare several variables of same type in one declaration
• Comma-separated list
int integer1, integer2, sum;

 2003 Prentice Hall, Inc. All rights reserved.


14
Another Simple Program:
Adding Two Integers
• Variables
– Variable names
• Valid identifier
– Series of characters (letters, digits, underscores)
– Cannot begin with digit
– Case sensitive
• C++ keywords cannot be used as identifiers or
variable names

 2003 Prentice Hall, Inc. All rights reserved.


15
Another Simple Program:
Adding Two Integers
• Input stream object
– >> (stream extraction operator)
• Used with std::cin
• Waits for user to input value, then press Enter (Return) key
• Stores value in variable to right of operator
– Converts value to variable data type
• = (assignment operator)
– Assigns value to variable
– Binary operator (two operands)
– Example:
sum = variable1 + variable2;

 2003 Prentice Hall, Inc. All rights reserved.


16
1 // Fig. 1.6: fig01_06.cpp
2 // Addition program.
Outline
3 #include <iostream>
4
fig01_06.cpp
5 // function main begins program execution
6 int main()
(1 of 1)
7 { Declare integer variables.
8 int integer1; // first number to be input by user
9 int integer2; // second number to be input by user
10 int sum; Usewhich
// variable in stream extraction
sum will be stored
11 operator with standard input
12 std::cout << "Enter first stream to obtain
integer\n"; user input.
// prompt
13 std::cin >> integer1; // read an integer
14
15 std::cout << "Enter second integer\n"; // prompt
16 std::cin >> integer2; // read
Calculations can an integer
be performed in output statements: alternative for
Stream manipulator
17 lines 18 and 20:
18 sum = integer1 + integer2; // assign result to sum
std::endl outputs a
19 std::cout << "Sum is " <<
newline, then “flushes output
integer1 + integer2 << std::endl;
20 std::cout << "Sum is " << sum << std::endl; // print sum buffer.”
21
22 return 0; // indicate that program ended successfully
23
24 } // end function main Concatenating, chaining or
cascading stream insertion
operations.

 2003 Prentice Hall, Inc.


All rights reserved.
17
Enter first integer
45
Outline
Enter second integer
72
fig01_06.cpp
Sum is 117
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
18

Memory Concepts

• Variable names
– Correspond to actual locations in computer's memory
– Every variable has name, type, size and value
– When new value placed into variable, overwrites previous
value
– Reading variables from memory nondestructive

 2003 Prentice Hall, Inc. All rights reserved.


19

Memory Concepts

std::cin >> integer1; integer1 45


– Assume user entered 45

std::cin >> integer2; integer1 45


– Assume user entered 72 integer2 72

sum = integer1 + integer2; integer1 45


integer2 72
sum 117

 2003 Prentice Hall, Inc. All rights reserved.


20

Arithmetic

• Arithmetic calculations
– *
• Multiplication
– /
• Division
• Integer division truncates remainder
– 7 / 5 evaluates to 1
– %
• Modulus operator returns remainder
– 7 % 5 evaluates to 2

 2003 Prentice Hall, Inc. All rights reserved.


21

Arithmetic

• Rules of operator precedence


– Operators in parentheses evaluated first
• Nested/embedded parentheses
– Operators in innermost pair first
– Multiplication, division, modulus applied next
• Operators applied from left to right
– Addition, subtraction applied last
Operator(s) • Operators applied fromOrder
Operation(s) left oftoevaluation
right (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Evaluated second. If there are several, they re
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.

 2003 Prentice Hall, Inc. All rights reserved.


Outline

Introduction to Programming

Chapter 2:
Control Statements

Dr. Mohammad A. Alzubaidi

Yarmouk University
Computer Engineering Department

 2003 Prentice Hall, Inc.


All rights reserved.
2

Introduction

• Before writing a program


– Have a thorough understanding of problem
– Carefully plan your approach for solving it
• While writing a program
– Know what “building blocks” are available
– Use good programming principles
• After writing a program
– Clear and documented
– Correct
– General
– High Efficiency

 2003 Prentice Hall, Inc. All rights reserved.


3

Algorithms

• Computing problems
– Solved by executing a series of actions in a specific order
• Algorithms are procedure determining
– Actions to be executed
– Order to be executed
– Example: recipe
• Program control
– Specifies the order in which statements are executed

 2003 Prentice Hall, Inc. All rights reserved.


4

Pseudocode

• Pseudocode
– Artificial, informal language used to develop algorithms
– Similar to everyday English
• Not executed on computers
– Used to think out program before coding
• Easy to convert into C++ program
– Only executable statements
• No need to declare variables

 2003 Prentice Hall, Inc. All rights reserved.


5

Control Structures

• Sequential execution
– Statements executed in order
• Transfer of control
– Next statement executed not next one in sequence
• 3 control structures
– Sequence structure
• Programs executed sequentially by default
– Selection structures
• if, if/else, switch
– Repetition structures
• while, do/while, for

 2003 Prentice Hall, Inc. All rights reserved.


6

Control Structures

• Flowchart
– Graphical representation of an algorithm
– Special-purpose symbols connected by arrows (flowlines)
– Rectangle symbol (action symbol)
• Any type of action
– Oval symbol
• Beginning or end of a program, or a section of code (circles)
• Single-entry/single-exit control structures
– Connect exit point of one to entry point of the next
– Control structure stacking
– Control structure nesting

 2003 Prentice Hall, Inc. All rights reserved.


7

if Selection Structure

• Selection structure
– Choose among alternative courses of action
– Pseudocode example:
If student’s grade is greater than or equal to 60
Print “Passed”
– If the condition is true
• Print statement executed, program continues to next statement
– If the condition is false
• Print statement ignored, program continues
– Indenting makes programs easier to read
• C++ ignores whitespace characters (tabs, spaces, etc.)

 2003 Prentice Hall, Inc. All rights reserved.


8

if Selection Structure

• Translation into C++


If student’s grade is greater than or equal to 60
Print “Passed”

if ( grade >= 60 )
cout << "Passed";

• Diamond symbol (decision symbol)


– Indicates decision is to be made
– Contains an expression that can be true or false
• Test condition, follow path
• if structure
– Single-entry/single-exit

 2003 Prentice Hall, Inc. All rights reserved.


9

if Selection Structure

• Flowchart of pseudocode statement

A decision can be made on


any expression.

true zero - false


grade >= 60 print “Passed”
nonzero - true
Example:
false 3 - 4 is true

 2003 Prentice Hall, Inc. All rights reserved.


10
Decision Making: Equality and Relational
Operators

Sta nd a rd a lg e b ra ic C++ e q ua lity Exa m p le Me a ning o f


e q ua lity o p e ra to r o r o r re la tio na l o f C++ C++ c o nd itio n
re la tio na l o p e ra to r o p e ra to r c o nd itio n

Relational operators
> > x > y x is greater than y
< < x < y x is less than y

 >= x >= y x is greater than or equal to y

 <= x <= y x is less than or equal to y

Equality operators
= == x == y x is equal to y

 != x != y x is not equal to y

 2003 Prentice Hall, Inc. All rights reserved.


11
1 // Fig. 1.14: fig01_14.cpp
2 // Using if statements, relational
Outline
3 // operators, and equality operators.
4 #include <iostream>
5
6 using std::cout; // program uses cout
7 using std::cin; // program uses cin
8 using std::endl; // program uses endl
9
10 // function main begins program execution
11 int main()
12 {
13 int num1; // first number to be read from user
14 int num2; // second number to be read from user
15
16 cout << "Enter two integers, and I will tell you\n"
17 << "the relationships they satisfy: ";
18 cin >> num1 >> num2; // read two integers
19
20 if ( num1 == num2 )
21 cout << num1 << " is equal to " << num2 << endl;
22
23 if ( num1 != num2 )
24 cout << num1 << " is not equal to " << num2 << endl;
25

 2003 Prentice Hall, Inc.


All rights reserved.
12
26 if ( num1 < num2 )
27 cout << num1 << " is less than " << num2 << endl;
Outline
28
29 if ( num1 > num2 )
30 cout << num1 << " is greater than " << num2 << endl;
31
32 if ( num1 <= num2 )
33 cout << num1 << " is less than or equal to "
34 << num2 << endl;
35
36 if ( num1 >= num2 )
37 cout << num1 << " is greater than or equal to "
38 << num2 << endl;
39
40 return 0; // indicate that program ended successfully
41
42 } // end function main

Enter two integers, and I will tell you


the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12

Enter two integers, and I will tell you


the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7
 2003 Prentice Hall, Inc.
All rights reserved.
13

Logical Operators

• Used as conditions in loops, if statements


• && (logical AND)
– true if both conditions are true
if ( gender == 1 && age >= 65 )
cout << “This is a senior Female" << endl;

• || (logical OR)
– true if either of condition is true
if ( semesterAverage >= 90 || finalExam >= 90 )
cout << "Student grade is A" << endl;

 2003 Prentice Hall, Inc. All rights reserved.


14

Logical Operators

• ! (logical NOT, logical negation)


– Returns true when its condition is false, & vice versa
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
Alternative:
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;

 2003 Prentice Hall, Inc. All rights reserved.


15
Confusing Equality (==) and Assignment (=)
Operators
• Common error
– Does not typically cause syntax errors
• Aspects of problem
– Expressions that have a value can be used for decision
• Zero = false, nonzero = true
– Assignment statements produce a value (the value to be
assigned)

 2003 Prentice Hall, Inc. All rights reserved.


16
Confusing Equality (==) and Assignment (=)
Operators
• Example
if ( payCode == 4 )
cout << "You get a bonus!" << endl;
– If paycode is 4, bonus given

• If == was replaced with =


if ( payCode = 4 )
cout << "You get a bonus!" << endl;
– Paycode set to 4 (no matter what it was before)
– Statement is true (since 4 is non-zero)
– Bonus given in every case

 2003 Prentice Hall, Inc. All rights reserved.


17
Confusing Equality (==) and Assignment (=)
Operators
• Lvalues
– Expressions that can appear on left side of equation
– Can be changed (I.e., variables)
• x = 4;
• Rvalues
– Only appear on right side of equation
– Constants, such as numbers (i.e. cannot write 4 = x;)
• Lvalues can be used as rvalues, but not vice versa

 2003 Prentice Hall, Inc. All rights reserved.


18

if/else Selection Structure

• if
– Performs action if condition true
• if/else
– Different actions if conditions true or false
• Pseudocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
• C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";

 2003 Prentice Hall, Inc. All rights reserved.


19

if/else Selection Structure

• Ternary conditional operator (?:)


– Three arguments (condition, value if true, value if false)
• Code could be written:
cout << ( grade >= 60 ? "Passed" : "Failed" );

Condition Value if true Value if false

false true
grade >= 60

print “Failed” print “Passed”

 2003 Prentice Hall, Inc. All rights reserved.


20

if/else Selection Structure

• Nested if/else structures


– One inside another, test for multiple cases
– Once condition met, other statements skipped
if student’s grade is greater than or equal to 90
Print “A”
else
if student’s grade is greater than or equal to 80
Print “B”
else
if student’s grade is greater than or equal to 70
Print “C”
else
if student’s grade is greater than or equal to 60
Print “D”
else
Print “F”

 2003 Prentice Hall, Inc. All rights reserved.


21

if/else Selection Structure

• Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";

 2003 Prentice Hall, Inc. All rights reserved.


22

if/else Selection Structure

• Compound statement
– Set of statements within a pair of braces
if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
– Without braces,
cout << "You must take this course again.\n";
always executed
• Block
– Set of statements within braces

 2003 Prentice Hall, Inc. All rights reserved.


23

switch Multiple-Selection Structure


• switch
– Test variable for multiple values
– Series of case labels and optional default case
switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch

case value2:
case value3: // taken if variable == value2 or == value3
statements
break;

default: // taken if variable matches no other cases


statements
break;
}

 2003 Prentice Hall, Inc. All rights reserved.


24

switch Multiple-Selection Structure

true
case a case a action(s) break

false

true
case b case b action(s) break

false

.
.
.

true
case z case z action(s) break
false

default action(s)

 2003 Prentice Hall, Inc. All rights reserved.


25
1 // Rating based on letter grades.
2 #include <iostream>
Outline
3 using namespace std;
4
5 void main()
6 {
7 char grade = 'D';
8 switch ( grade ) {
9 case 'A':
10 cout << "Excellent!" << endl;
11 break;
12 case 'B':
13 case 'C':
14 cout << "Well done" << endl;
15 break;
16 case 'D':
17 cout << "You passed" << endl;
18 break;
19 case 'F':
20 cout << "Better try again" << endl;
21 break;
22 default:
23 cout << "Invalid grade" << endl;
24 break;
25 }
26 cout << "Your grade is " << grade << endl;
27 }

You passed
Your grade is D
 2003 Prentice Hall, Inc.
All rights reserved.
26

while Repetition Structure

• Repetition structure
– Action repeated while some condition remains true
– Pseudocode
while there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false
• Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;

 2003 Prentice Hall, Inc. All rights reserved.


27

The while Repetition Structure

• Flowchart of while loop

true
product <= 1000 product = 2 * product

false

 2003 Prentice Hall, Inc. All rights reserved.


28
Formulating Algorithms
(Counter-Controlled Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches certain value
• Definite repetition
– Number of repetitions known
• Example
A class of ten students took a quiz. The grades (integers in
the range 0 to 100) for this quiz are available to you.
Determine the class average on the quiz.

 2003 Prentice Hall, Inc. All rights reserved.


29
Formulating Algorithms
(Counter-Controlled Repetition)
• Pseudocode for example:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average

• Next: C++ code for this example

 2003 Prentice Hall, Inc. All rights reserved.


30
1 // Fig. 2.7: fig02_07.cpp
2 // Class average program with counter-controlled repetition.
Outline
3 #include <iostream>
4
fig02_07.cpp
5 using std::cout;
6 using std::cin;
(1 of 2)
7 using std::endl;
8
9 // function main begins program execution
10 int main()
11 {
12 int total; // sum of grades input by user
13 int gradeCounter; // number of grade to be entered next
14 int grade; // grade value
15 int average; // average of grades
16
17 // initialization phase
18 total = 0; // initialize total
19 gradeCounter = 1; // initialize loop counter
20

 2003 Prentice Hall, Inc.


All rights reserved.
31
21 // processing phase
22 while ( gradeCounter <= 10 ) { // loop 10 times
Outline
23 cout << "Enter grade: "; // prompt for input
24 cin >> grade; // read grade from user
fig02_07.cpp
25 total = total + grade; // add grade to total
26 gradeCounter = gradeCounter + 1; // increment counter
(2 of 2)
27 }
28 fig02_07.cpp
29 // termination phase output (1 of 1)
30 average = total / 10; // integer division
31
32 // display result
33 cout << "Class average is " << average << endl;
The counter gets incremented each
34
35 return 0; // indicate
time the loop executes.
program ended successfully
36 Eventually, the counter causes the
37 } // end function main loop to end.

Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81  2003 Prentice Hall, Inc.
All rights reserved.
32
Formulating Algorithms
(Sentinel-Controlled Repetition)
• Suppose problem becomes:
Develop a class-averaging program that will process an
arbitrary number of grades each time the program is run
– Unknown number of students
– How will program know when to end?
• Sentinel value
– Indicates “end of data entry”
– Loop ends when sentinel input
– Sentinel chosen so it cannot be confused with regular input
• -1 in this case

 2003 Prentice Hall, Inc. All rights reserved.


33
Formulating Algorithms
(Sentinel-Controlled Repetition)
• Top-down, stepwise refinement
– Begin with pseudocode representation of top
Determine the class average for the quiz
– Divide top into smaller tasks, list in order
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average

 2003 Prentice Hall, Inc. All rights reserved.


34
Formulating Algorithms
(Sentinel-Controlled Repetition)
• Many programs have three phases
– Initialization
• Initializes the program variables
– Processing
• Input data, adjusts program variables
– Termination
• Calculate and print the final results
– Helps break up programs for top-down refinement

 2003 Prentice Hall, Inc. All rights reserved.


35
Formulating Algorithms
(Sentinel-Controlled Repetition)
• Refine the initialization phase
Initialize variables
goes to
Initialize total to zero
Initialize counter to zero
• Processing
Input, sum and count the quiz grades
goes to
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)

 2003 Prentice Hall, Inc. All rights reserved.


36
Formulating Algorithms
(Sentinel-Controlled Repetition)
• Termination
Calculate and print the class average
goes to
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
Else
Print “No grades were entered”
• Next: C++ program

 2003 Prentice Hall, Inc. All rights reserved.


37
1 // Fig. 2.9: fig02_09.cpp
2 // Class average program with sentinel-controlled repetition.
Outline
3 #include <iostream>
4
fig02_09.cpp
5 using std::cout;
6 using std::cin;
(1 of 3)
7 using std::endl;
8 using std::fixed;
9
10 #include <iomanip> // parameterized stream manipulators
11
12 using std::setprecision; // sets numeric output precision
13
14 // function main begins program execution
15 int main()
16 { Data type double used to represent
17 int total; // sum of grades decimal numbers.
18 int gradeCounter; // number of grades entered
19 int grade; // grade value
20
21 double average; // number with decimal point for average
22
23 // initialization phase
24 total = 0; // initialize total
25 gradeCounter = 0; // initialize loop counter

 2003 Prentice Hall, Inc.


All rights reserved.
38
26
27 // processing phase
Outline
28 // get first grade from user
29 cout << "Enter grade, -1 to end: "; // prompt for input
fig02_09.cpp
30 cin >> grade; // read grade from user
31
(2 of 3)
32 // loop until sentinel value read from user
33 while ( grade != -1 )static_cast<double>()
{ treats total as a
34 double temporarily
total = total + grade; (casting).
// add grade to total
35 gradeCounter = gradeCounter + 1; // increment counter
36 Required because dividing two integers truncates the
37 cout << "Enter grade, -1 to end: "; // prompt for input
remainder.
38 cin >> grade; // read next grade
39
40 } // end while
gradeCounter is an int, but it gets promoted to
41
double.
42 // termination phase
43 // if user entered at least one grade ...
44 if ( gradeCounter != 0 ) {
45
46 // calculate average of all grades entered
47 average = static_cast< double >( total ) / gradeCounter;
48

 2003 Prentice Hall, Inc.


All rights reserved.
39
49 // display average with two digits of precision
50 cout << "Class average is " << setprecision( 2 )
Outline
51 << fixed << average << endl;
52
fig02_09.cpp
53 } // end if part of if/else
54
(3 of 3)
55 else // if no grades were entered, output appropriate message
56 cout << "No grades were entered" << endl; fig02_09.cpp
57 output (1 of 1)
58 return 0; // indicate program ended successfully
59
60 } // end function main

fixed forces output setprecision(2)prints


to print two digits past
Enter grade, -1 to end: 75 decimal
in fixed point format (not point (rounded to fit precision).
Enter grade, -1 to end: 94
scientific notation). Also,
Enter grade, -1 to end: 97
forces trailing zerosPrograms
and that use this must include <iomanip>
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70 decimal point to print.
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83 Include <iostream>
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50

 2003 Prentice Hall, Inc.


All rights reserved.
40

Nested Control Structures

• Problem statement
A college has a list of test results (1 = pass, 2 = fail) for 10
students. Write a program that analyzes the results. If more
than 8 students pass, print "Raise Tuition".
• Notice that
– Program processes 10 results
• Fixed number, use counter-controlled loop
– Two counters can be used
• One counts number that passed
• Another counts number that fail
– Each test result is 1 or 2
• If not 1, assume 2

 2003 Prentice Hall, Inc. All rights reserved.


41

Nested Control Structures

• Top level outline


Analyze exam results and decide if tuition should be raised
• First refinement
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition
should be raised
• Refine
Initialize variables
to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one

 2003 Prentice Hall, Inc. All rights reserved.


42

Nested Control Structures

• Refine
Input the ten quiz grades and count passes and failures
to
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
Else
Add one to failures
Add one to student counter

 2003 Prentice Hall, Inc. All rights reserved.


43

Nested Control Structures

• Refine
Print a summary of the exam results and decide if tuition should
be raised
to
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
• Program next

 2003 Prentice Hall, Inc. All rights reserved.


44
1 // Fig. 2.11: fig02_11.cpp
2 // Analysis of examination results.
Outline
3 #include <iostream>
4
fig02_11.cpp
5 using std::cout;
6 using std::cin;
(1 of 2)
7 using std::endl;
8
9 // function main begins program execution
10 int main()
11 {
12 // initialize variables in declarations
13 int passes = 0; // number of passes
14 int failures = 0; // number of failures
15 int studentCounter = 1; // student counter
16 int result; // one exam result
17
18 // process 10 students using counter-controlled loop
19 while ( studentCounter <= 10 ) {
20
21 // prompt user for input and obtain value from user
22 cout << "Enter result (1 = pass, 2 = fail): ";
23 cin >> result;
24

 2003 Prentice Hall, Inc.


All rights reserved.
45
25 // if result 1, increment passes; if/else nested in while
26 if ( result == 1 ) // if/else nested in while
Outline
27 passes = passes + 1;
28
fig02_11.cpp
29 else // if result not 1, increment failures
30 failures = failures + 1;
(2 of 2)
31
32 // increment studentCounter so loop eventually terminates
33 studentCounter = studentCounter + 1;
34
35 } // end while
36
37 // termination phase; display number of passes and failures
38 cout << "Passed " << passes << endl;
39 cout << "Failed " << failures << endl;
40
41 // if more than eight students passed, print "raise tuition"
42 if ( passes > 8 )
43 cout << "Raise tuition " << endl;
44
45 return 0; // successful termination
46
47 } // end function main

 2003 Prentice Hall, Inc.


All rights reserved.
46
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
Outline
Enter result (1 = pass, 2 = fail): 2
Enter result (1 = pass, 2 = fail): 1
fig02_11.cpp
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
output (1 of 1)
Enter result (1 = pass, 2 = fail): 2
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
Passed 6
Failed 4

Enter result (1 = pass, 2 = fail): 1


Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Passed 9
Failed 1
Raise tuition

 2003 Prentice Hall, Inc.


All rights reserved.
47

Assignment Operators

• Assignment expression abbreviations


– Addition assignment operator
c = c + 3; abbreviated to
c += 3;
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Other assignment operators
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
 2003 Prentice Hall, Inc. All rights reserved.
48

Increment and Decrement Operators


• Increment operator (++) - can be used instead of c
+= 1
• Decrement operator (--) - can be used instead of c -
= 1
– Preincrement
• When the operator is used before the variable (++c or –c)
• Variable is changed, then the expression it is in is evaluated.
– Posincrement
• When the operator is used after the variable (c++ or c--)
• Expression the variable is in executes, then the variable is changed.

 2003 Prentice Hall, Inc. All rights reserved.


49

Increment and Decrement Operators

• Increment operator (++)


– Increment variable by one
– c++
• Same as c += 1
• Decrement operator (--) similar
– Decrement variable by one
– c--

 2003 Prentice Hall, Inc. All rights reserved.


50

Increment and Decrement Operators

• Preincrement
– Variable changed before used in expression
• Operator before variable (++c or --c)
• Postincrement
– Incremented changed after expression
• Operator after variable (c++, c--)

 2003 Prentice Hall, Inc. All rights reserved.


51

Increment and Decrement Operators

• If c = 5, then
– cout << ++c;
• c is changed to 6, then printed out
– cout << c++;
• Prints out 5 (cout is executed before the increment.
• c then becomes 6

 2003 Prentice Hall, Inc. All rights reserved.


52

Increment and Decrement Operators

• When variable not in expression


– Preincrementing and postincrementing have same effect
++c;
cout << c;
and
c++;
cout << c;

are the same

 2003 Prentice Hall, Inc. All rights reserved.


53
1 // Fig. 2.14: fig02_14.cpp
2 // Preincrementing and postincrementing.
Outline
3 #include <iostream>
4
fig02_14.cpp
5 using std::cout;
6 using std::endl;
(1 of 2)
7
8 // function main begins program execution
9 int main()
10 {
11 int c; // declare variable
12
13 // demonstrate postincrement
14 c = 5; // assign 5 to c
15 cout << c << endl; // print 5
16 cout << c++ << endl; // print 5 then postincrement
17 cout << c << endl << endl; // print 6
18
19 // demonstrate preincrement
20 c = 5; // assign 5 to c
21 cout << c << endl; // print 5
22 cout << ++c << endl; // preincrement then print 6
23 cout << c << endl; // print 6

 2003 Prentice Hall, Inc.


All rights reserved.
54
24
25 return 0; // indicate successful termination
Outline
26
27 } // end function main
fig02_14.cpp
(2 of 2)
5
5
6
fig02_14.cpp
output (1 of 1)
5
6
6

 2003 Prentice Hall, Inc.


All rights reserved.
55

Nested Control Structures

• Example upcoming
– Program to read grades (A-F)
– Display number of each grade entered
• Details about characters
– Single characters typically stored in a char data type
• char a 1-byte integer, so chars can be stored as ints
– Can treat character as int or char
• 97 is the numerical representation of lowercase ‘a’ (ASCII)
• Use single quotes to get numerical representation of character
cout << "The character (" << 'a' << ") has the value "
<< static_cast< int > ( 'a' ) << endl;
Prints
The character (a) has the value 97

 2003 Prentice Hall, Inc. All rights reserved.


56
1 // Fig. 2.22: fig02_22.cpp
2 // Counting letter grades.
Outline
3 #include <iostream>
4
fig02_22.cpp
5 using std::cout;
6 using std::cin;
(1 of 4)
7 using std::endl;
8
9 // function main begins program execution
10 int main()
11 {
12 char grade; // one grade
13 int aCount = 0; // number of As
14 int bCount = 0; // number of Bs
15 int cCount = 0; // number of Cs
16 int dCount = 0; // number of Ds
17 int fCount = 0; // number of Fs
18
19 cout << "Enter the letter grades." << endl
20 << "Enter the EOF character to end input." << endl;
21

 2003 Prentice Hall, Inc.


All rights reserved.
57
22 // loop until user types end-of-file key sequence
23 while ( ( grade = cin.get() ) != EOF ) { break causes switch to end and
Outline
24 the program continues with the first
25 // determine which grade was input statement after the switch fig02_22.cpp
26 switch ( grade ) { // switch structure nested in while
structure. (2 of 4)
27
28 case 'A': // grade was uppercase A
cin.get() uses dot notation
29 case 'a': // or lowercase a
30 ++aCount; // increment aCount (explained chapter 6). This
31 break; // necessary to exit switch function gets 1 character from the
32 Assignment statements have a keyboard (after Enter pressed), and
33 case 'B': value, was
// grade which is the same
uppercase B as it is assigned to grade.
34 case 'b': thelowercase
// or variable onb the left of the
35 ++bCount; =. The value
// increment of this statement cin.get() returns EOF (end-of-
bCount
36 break; // exit
is theswitch
same as the value
Compares grade to the file) after the EOF character is
37 returned by cin.get(). input, to indicate the end of data.
38numerical representations
case 'C': of // grade was uppercase C
39A and a. case 'c': // or lowercase c
EOF may be ctrl-d or ctrl-z,
This can also be used to depending on your OS.
40 ++cCount; // increment cCount
41 break;
initialize multiple variables:
// exit switch
42
a = b = c = 0;

 2003 Prentice Hall, Inc.


All rights reserved.
58
43 case 'D': // grade was uppercase D
44 case 'd': // or lowercase d
Outline
45 ++dCount; // increment dCount
46 break; // exit switch
fig02_22.cpp
47 This test is necessary because
48 case 'F': // grade was Enter
uppercase F
(3 of 4)
is pressed after each
49 case 'f': // or lowercase f
letter grade is input. This adds
50 ++fCount; // increment fCount
a newline character that must
51 break; // exit switch
52
be removed. Likewise, we
53 case '\n': // want to ignore any
ignore newlines,
54 case '\t': // tabs, whitespace.
55 case ' ': // and spaces in input
56 break; Notice the default
// exit switch statement, which
57 catches all other cases.
58 default: // catch all other characters
59 cout << "Incorrect letter grade entered."
60 << " Enter a new grade." << endl;
61 break; // optional; will exit switch anyway
62
63 } // end switch
64
65 } // end while
66

 2003 Prentice Hall, Inc.


All rights reserved.
59
67 // output summary of results
68 cout << "\n\nTotals for each letter grade are:"
Outline
69 << "\nA: " << aCount // display number of A grades
70 << "\nB: " << bCount // display number of B grades
fig02_22.cpp
71 << "\nC: " << cCount // display number of C grades
72 << "\nD: " << dCount // display number of D grades
(4 of 4)
73 << "\nF: " << fCount // display number of F grades
74 << endl;
75
76 return 0; // indicate successful termination
77
78 } // end function main

 2003 Prentice Hall, Inc.


All rights reserved.
60
Enter the letter grades.
Enter the EOF character to end input.
Outline
a
B
fig02_22.cpp
c
C
output (1 of 1)
A
d
f
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
b
^Z

Totals for each letter grade are:


A: 3
B: 2
C: 3
D: 2
F: 1

 2003 Prentice Hall, Inc.


All rights reserved.
61
1
2
Outline
3
4
fig02_16.cpp
5
6
output (1 of 1)
7
8
9
10

 2003 Prentice Hall, Inc.


All rights reserved.
62

for Repetition Structure


• General format when using for loops
for ( initialization; LoopContinuationTest;
increment )
statement

• Example
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
– Prints integers from one to ten
No
semicolon
after last
statement

 2003 Prentice Hall, Inc. All rights reserved.


63
1 // Fig. 2.17: fig02_17.cpp
2 // Counter-controlled repetition with the for structure.
Outline
3 #include <iostream>
4
fig02_17.cpp
5 using std::cout;
6 using std::endl;
(1 of 1)
7
8 // function main begins program execution
9 int main()
10 {
11 // Initialization, repetition condition and incrementing
12 // are all included in the for structure header.
13
14 for ( int counter = 1; counter <= 10; counter++ )
15 cout << counter << endl;
16
17 return 0; // indicate successful termination
18
19 } // end function main

 2003 Prentice Hall, Inc.


All rights reserved.
64
1
2
Outline
3
4
fig02_17.cpp
5
6
output (1 of 1)
7
8
9
10

 2003 Prentice Hall, Inc.


All rights reserved.
65

for Repetition Structure


• for loops can usually be rewritten as while loops
initialization;
while ( loopContinuationTest){
statement
increment;
}

• Initialization and increment


– For multiple variables, use comma-separated lists
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;

 2003 Prentice Hall, Inc. All rights reserved.


66
1 // Fig. 2.20: fig02_20.cpp
2 // Summation with for.
Outline
3 #include <iostream>
4
fig02_20.cpp
5 using std::cout;
6 using std::endl;
(1 of 1)
7
8 // function main begins program execution fig02_20.cpp
9 int main() output (1 of 1)
10 {
11 int sum = 0; // initialize sum
12
13 // sum even integers from 2 through 100
14 for ( int number = 2; number <= 100; number += 2 )
15 sum += number; // add number to sum
16
17 cout << "Sum is " << sum << endl; // output sum
18 return 0; // successful termination
19
20 } // end function main

Sum is 2550

 2003 Prentice Hall, Inc.


All rights reserved.
67

Examples Using the for Structure

• Program to calculate compound interest


• A person invests $1000.00 in a savings account yielding 5 percent
interest. Assuming that all interest is left on deposit in the account,
calculate and print the amount of money in the account at the end of
each year for 10 years. Use the following formula for determining
these amounts:
n
a = p(1+r)
• p is the original amount invested (i.e., the principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the nth year

 2003 Prentice Hall, Inc. All rights reserved.


68
1 // Fig. 2.21: fig02_21.cpp
2 // Calculating compound interest.
Outline
3 #include <iostream>
4
fig02_21.cpp
5 using std::cout;
6 using std::endl;
(1 of 2)
7 using std::ios;
8 using std::fixed;
9
10 #include <iomanip>
11 <cmath> header needed for
12 using std::setw; the pow function (program
13 using std::setprecision; will not compile without it).
14
15 #include <cmath> // enables program to use function pow
16
17 // function main begins program execution
18 int main()
19 {
20 double amount; // amount on deposit
21 double principal = 1000.0; // starting principal
22 double rate = .05; // interest rate
23

 2003 Prentice Hall, Inc.


All rights reserved.
69
24 // output table column heads
25 cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;
Outline
26
Sets the field width to at least
27 // set floating-point number format
21 characters. If output less fig02_21.cpp
28 cout << fixed << setprecision( 2 );
29
than 21, it is right-justified. (2 of 2)
30 // calculate amount on deposit for each of ten years
31 for ( int year = 1; year <= 10; year++ ) {
32
pow(x,y) = x raised to the
33 // calculate new amount for specified year yth power.
34 amount = principal * pow( 1.0 + rate, year );
35
36 // output one table row
37 cout << setw( 4 ) << year
38 << setw( 21 ) << amount << endl;
39
40 } // end for
41
42 return 0; // indicate successful termination
43
44 } // end function main

 2003 Prentice Hall, Inc.


All rights reserved.
70
Year Amount on deposit
1 1050.00
Outline
2 1102.50
3 1157.63
fig02_21.cpp
4 1215.51
5 1276.28
output (1 of 1)
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89

Numbers are right-justified


due to setw statements (at
positions 4 and 21).

 2003 Prentice Hall, Inc.


All rights reserved.
71

do/while Repetition Structure

• Similar to while structure


– Makes loop continuation test at end, not beginning
– Loop body executes at least once
• Format
do {
statement
} while ( condition ); action(s)

true
condition

false

 2003 Prentice Hall, Inc. All rights reserved.


72
1 // Fig. 2.24: fig02_24.cpp
2 // Using the do/while repetition structure.
Outline
3 #include <iostream>
4
fig02_24.cpp
5 using std::cout;
6 using std::endl;
(1 of 1)
7
8 // function main begins program execution fig02_24.cpp
9 int main() output (1 of 1)
10 {
11 int counter = 1; // initialize counter
12 Notice the preincrement in
13 do { loop-continuation test.
14 cout << counter << " "; // display counter
15 } while ( ++counter <= 10 ); // end do/while
16
17 cout << endl;
18
19 return 0; // indicate successful termination
20
21 } // end function main

1 2 3 4 5 6 7 8 9 10

 2003 Prentice Hall, Inc.


All rights reserved.
73

break and continue Statements

• break statement
– Immediate exit from while, for, do/while, switch
– Program continues with first statement after structure
• Common uses
– Escape early from a loop
– Skip the remainder of switch

 2003 Prentice Hall, Inc. All rights reserved.


74
1 // Fig. 2.26: fig02_26.cpp
2 // Using the break statement in a for structure.
Outline
3 #include <iostream>
4
fig02_26.cpp
5 using std::cout;
6 using std::endl;
(1 of 2)
7
8 // function main begins program execution
9 int main()
10 {
11
12 int x; // x declared here so it can be used after the loop
13
14 // loop 10 times
15 for ( x = 1; x <= 10; x++ ) { Exits for structure when
16 break executed.
17 // if x is 5, terminate loop
18 if ( x == 5 )
19 break; // break loop only if x is 5
20
21 cout << x << " "; // display value of x
22
23 } // end for
24
25 cout << "\nBroke out of loop when x became " << x << endl;

 2003 Prentice Hall, Inc.


All rights reserved.
75
26
27 return 0; // indicate successful termination
Outline
28
29 } // end function main
fig02_26.cpp
(2 of 2)
1 2 3 4
Broke out of loop when x became 5
fig02_26.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
76

break and continue Statements

• continue statement
– Used in while, for, do/while
– Skips remainder of loop body
– Proceeds with next iteration of loop
• while and do/while structure
– Loop-continuation test evaluated immediately after the
continue statement
• for structure
– Increment expression executed
– Next, loop-continuation test evaluated

 2003 Prentice Hall, Inc. All rights reserved.


77
1 // Fig. 2.27: fig02_27.cpp
2 // Using the continue statement in a for structure.
Outline
3 #include <iostream>
4
fig02_27.cpp
5 using std::cout;
6 using std::endl;
(1 of 2)
7
8 // function main begins program execution
9 int main()
10 {
11 // loop 10 times
12 for ( int x = 1; x <= 10; x++ ) {
13 Skips to next iteration of the
14 // if x is 5, continue with loop.
next iteration of loop
15 if ( x == 5 )
16 continue; // skip remaining code in loop body
17
18 cout << x << " "; // display value of x
19
20 } // end for structure
21
22 cout << "\nUsed continue to skip printing the value 5"
23 << endl;
24
25 return 0; // indicate successful termination

 2003 Prentice Hall, Inc.


All rights reserved.
78
26
27 } // end function main
Outline

1 2 3 4 6 7 8 9 10 fig02_27.cpp
Used continue to skip printing the value 5 (2 of 2)

fig02_27.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
79

Structured-Programming Summary

• All programs broken down into


– Sequence
– Selection
• if, if/else, or switch
• Any selection can be rewritten as an if statement
– Repetition
• while, for or do/while
• Any repetition structure can be rewritten as a while statement

 2003 Prentice Hall, Inc. All rights reserved.


Outline

Intro to Programming

Chapter 3:
Functions

Dr. Mohammad A. Alzubaidi

Yarmouk University
Computer Engineering Dept.

 2003 Prentice Hall, Inc.


All rights reserved.
2

Introduction

• Divide and conquer


– Construct a program from smaller pieces or components
– Each piece more manageable than the original program

 2003 Prentice Hall, Inc. All rights reserved.


3

Program Components in C++

• Modules: functions and classes


• Programs use new and “prepackaged” modules
– User-defined: programmer-defined functions, classes
– Prepackaged: from the standard library
• Functions invoked by function call
– Function name and information (arguments) it needs
• Function definitions
– Only written once
– Hidden from other functions

 2003 Prentice Hall, Inc. All rights reserved.


4

Math Library Functions

• Perform common mathematical calculations


– Include the header file <cmath>
• Functions called by writing
– functionName (argument);
or
– functionName(argument1, argument2, …);
• Example
cout << sqrt( 900.0 );
– sqrt (square root) function The preceding statement would
print 30
– All functions in math library return a double

 2003 Prentice Hall, Inc. All rights reserved.


5

Math Library Functions

• Function arguments can be


– Constants
• sqrt( 4 );
– Variables
• sqrt( x );
– Expressions
• sqrt( sqrt( x ) ) ;
• sqrt( 3 - 6x );

 2003 Prentice Hall, Inc. All rights reserved.


6
M e tho d De sc rip tio n Exa m p le
ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0
not greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992
point number
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)
Fig . 3.2 M a th lib ra ry func tio ns.
 2003 Prentice Hall, Inc. All rights reserved.
7

Functions

• Functions
– Modularize a program
– Software reusability
• Call function multiple times
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local
variables
• Parameters
– Local variables passed to function when called
– Provide outside information

 2003 Prentice Hall, Inc. All rights reserved.


8

Function Definitions

• Function prototype
– Tells compiler argument type and return type of function
– int square( int );
• Function takes an int and returns an int
– Explained in more detail later

• Calling/invoking a function
– square(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result

 2003 Prentice Hall, Inc. All rights reserved.


9

Function Definitions

• Format for function definition


return-value-type function-name( parameter-list )
{
declarations and statements
}
– Parameter list
• Comma separated list of arguments
– Data type needed for each argument
• If no arguments, use void or leave blank
– Return-value-type
• Data type of result returned (use void if nothing returned)

 2003 Prentice Hall, Inc. All rights reserved.


10

Function Definitions

• Example function
int square( int y )
{
return y * y;
}

• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
• Functions cannot be defined inside other functions
• Next: program examples

 2003 Prentice Hall, Inc. All rights reserved.


11
1 // Fig. 3.3: fig03_03.cpp
2 // Creating and using a programmer-defined function.
Outline
3 #include <iostream>
4 Function prototype: specifies fig03_03.cpp
5 using std::cout; data types of arguments and
6 using std::endl;
(1 of 2)
return values. square
7
expects and int, and returns
8 int square( int ); // function prototype
an int.
9
10 int main()
11 { Parentheses () cause
12 // loop 10 times and calculate and output
function to be called. When
13 // square of x each time
14 for ( int x = 1; x <= 10; x++ )
done, it returns the result.
15 cout << square( x ) << " "; // function call
16
17 cout << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main
22

 2003 Prentice Hall, Inc.


All rights reserved.
12
23 // square function definition returns square of an integer
24 int square( int y ) // y is a copy of argument to function
Outline
25 {
26 return y * y; // returns square of y as an int
fig03_03.cpp
27
28 } // end function square
(2 of 2)
Definition of square. y is a
copy of the argument passed. fig03_03.cpp
1 4 9 16 25 36 49 64 81 100 Returns y * y, or y squared. output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
13
1 // Fig. 3.4: fig03_04.cpp
2 // Finding the maximum of three floating-point numbers.
Outline
3 #include <iostream>
4
fig03_04.cpp
5 using std::cout;
6 using std::cin;
(1 of 2)
7 using std::endl;
8
9 double maximum( double, double, double ); // function prototype
10
11 int main()
12 {
13 double number1;
Function maximum takes 3
14 double number2;
15 double number3;
arguments (all double) and
16
returns a double.
17 cout << "Enter three floating-point numbers: ";
18 cin >> number1 >> number2 >> number3;
19
20 // number1, number2 and number3 are arguments to
21 // the maximum function call
22 cout << "Maximum is: "
23 << maximum( number1, number2, number3 ) << endl;
24
25 return 0; // indicates successful termination

 2003 Prentice Hall, Inc.


All rights reserved.
14
26
27 } // end main
Outline
28 Comma separated list for
29 // function maximum definition; multiple parameters.
fig03_04.cpp
30 // x, y and z are parameters
31 double maximum( double x, double y, double z )
(2 of 2)
32 {
33 double max = x; // assume x is largest fig03_04.cpp
34 output (1 of 1)
35 if ( y > max ) // if y is larger,
36 max = y; // assign y to max
37
38 if ( z > max ) // if z is larger,
39 max = z; // assign z to max
40
41 return max; // max is largest value
42
43 } // end function maximum

Enter three floating-point numbers: 99.32 37.3 27.1928


Maximum is: 99.32

Enter three floating-point numbers: 1.1 3.333 2.22


Maximum is: 3.333

Enter three floating-point numbers: 27.9 14.31 88.99


Maximum is: 88.99

 2003 Prentice Hall, Inc.


All rights reserved.
15

Function Prototypes

• Function prototype contains


– Function name
– Parameters (number and data type)
– Return type (void if returns nothing)
– Only needed if function definition after function call
• Prototype must match function definition
– Function prototype
double maximum( double, double, double );
– Definition
double maximum( double x, double y, double z )
{

}

 2003 Prentice Hall, Inc. All rights reserved.


16

Function Prototypes

• Function signature
– Part of prototype with name and parameters
• double maximum( double, double, double );

Function signature
• Argument Coercion
– Force arguments to be of proper type
• Converting int (4) to double (4.0)
cout << sqrt(4)
– Conversion rules
• Arguments usually converted automatically
• Changing from double to int can truncate data
– 3.4 to 3
– Mixed type goes to highest type (promotion)
• Int * double

 2003 Prentice Hall, Inc. All rights reserved.


17

Function Prototypes

Da ta typ es
long double
double
float
unsigned long int (synonymous with unsigned long)
long int (synonymous with long)
unsigned int (synonymous with unsigned)
int
unsigned short int (synonymous with unsigned short)
short int (synonymous with short)
unsigned char
char
bool (false becomes 0, true becomes 1)
Fig . 3.5 Pro m o tio n hiera rc hy fo r b uilt-in d a ta typ es.

 2003 Prentice Hall, Inc. All rights reserved.


18

Functions with Empty Parameter Lists

• Empty parameter lists


– void or leave parameter list empty
– Indicates function takes no arguments
– Function print takes no arguments and returns no value
• void print();
• void print( void );

 2003 Prentice Hall, Inc. All rights reserved.


19
1 // Fig. 3.18: fig03_18.cpp
2 // Functions that take no arguments.
Outline
3 #include <iostream>
4
fig03_18.cpp
5 using std::cout;
6 using std::endl;
(1 of 2)
7
8 void function1(); // function prototype
9 void function2( void ); // function prototype
10
11 int main()
12 {
13 function1(); // call function1 with no arguments
14 function2(); // call function2 with no arguments
15
16 return 0; // indicates successful termination
17
18 } // end main
19

 2003 Prentice Hall, Inc.


All rights reserved.
20
20 // function1 uses an empty parameter list to specify that
21 // the function receives no arguments
Outline
22 void function1()
23 {
fig03_18.cpp
24 cout << "function1 takes no arguments" << endl;
25
(2 of 2)
26 } // end function1
27 fig03_18.cpp
28 // function2 uses a void parameter list to specify that output (1 of 1)
29 // the function receives no arguments
30 void function2( void )
31 {
32 cout << "function2 also takes no arguments" << endl;
33
34 } // end function2

function1 takes no arguments


function2 also takes no arguments

 2003 Prentice Hall, Inc.


All rights reserved.
21

Header Files

• Header files contain


– Function prototypes
– Definitions of data types and constants
• Header files ending with .h
– Programmer-defined header files
#include “myheader.h”
• Library header files
#include <cmath>

 2003 Prentice Hall, Inc. All rights reserved.


22

Storage Classes

• Variables have attributes


– Have seen name, type, size, value
– Storage class
• How long variable exists in memory
– Scope
• Where variable can be referenced in program

 2003 Prentice Hall, Inc. All rights reserved.


23

Storage Classes

• Automatic storage class


– Variable created when program enters its block
– Variable destroyed when program leaves block
– Only local variables of functions can be automatic
• Automatic by default
• keyword auto explicitly declares automatic

 2003 Prentice Hall, Inc. All rights reserved.


24

Storage Classes
• Static storage class
– Variables exist for entire program
• For functions, name exists for entire program
– May not be accessible, scope rules still apply (more later)
• static keyword
– Local variables in function
– Initialized to zero
– Keeps value between function calls
– Only known in own function
• extern keyword
– Default for global variables/functions
• Globals: defined outside of a function block
– Known in any function that comes after it
 2003 Prentice Hall, Inc. All rights reserved.
25

Scope Rules

• Scope
– Portion of program where identifier can be used
• File scope
– Defined outside a function, known in all functions
– Global variables, function definitions and prototypes
• Function scope
– Can only be referenced inside defining function

 2003 Prentice Hall, Inc. All rights reserved.


26

Scope Rules

• Block scope
– Begins at declaration, ends at right brace }
• Can only be referenced in this range
– Local variables, function parameters
• Function-prototype scope
– Parameter list of prototype
– Names in prototype optional
• Compiler ignores
– In a single prototype, name can be used once

 2003 Prentice Hall, Inc. All rights reserved.


27
#include <iostream>
using namespace std;
Outline

int i = 8;
fig03_12.cpp
int square(int i);
(1 of 5)
int main()
{
cout << "Value of i is: " << i << endl;
{
int i = 6;
cout << "Value of i is: " << i << endl;
}
int i = 7;
cout << "Value of i is: " << i << endl;
i = square(i);
cout << "Value of i is: " << i << endl;

return 0;
}

int square(int i){


//int i; Causes an error here because variable name I used two times with equivalent scope
cout << "Value of i is: " << i << endl;
return i; Value of i is: 8
}
Value of i is: 6
Value of i is: 7
Value of i is: 7
 2003 Prentice Hall, Inc.
Value of i is: 7 All rights reserved.
28
1 // Fig. 3.12: fig03_12.cpp
2 // A scoping example.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 void useLocal( void ); // function prototype
9 void useStaticLocal( void ); // function prototype
10 void useGlobal( void ); // function prototype
11
12 int x = 1; // global variable
13
14 int main()
15 {
16 int x = 5; // local variable to main
17
18 cout << "local x in main's outer scope is " << x << endl;
19
20 { // start new scope
21
22 int x = 7;
23
24 cout << "local x in main's inner scope is " << x << endl;
25
26 } // end new scope
27
28 cout << "local x in main's outer scope is " << x << endl;
29
 2003 Prentice
30 useLocal(); //reserved.
Hall, Inc. All rights useLocal has local x http://www.deitel.com
31 useStaticLocal(); // useStaticLocal has static local x
29
32 useGlobal(); // useGlobal uses global x
33 useLocal(); // useLocal reinitializes its local x
34 useStaticLocal(); // static local x retains its prior value
35 useGlobal(); // global x also retains its value
36
37 cout << "\nlocal x in main is " << x << endl;
38
39 return 0; // indicates successful termination
40
41 } // end main
42
43 // useLocal reinitializes local variable x during each call
44 void useLocal( void )
45 {
46 int x = 25; // initialized each time useLocal is called
47
48 cout << endl << "local x is " << x
49 << " on entering useLocal" << endl;
50 ++x;
51 cout << "local x is " << x
52 << " on exiting useLocal" << endl;
53
54 } // end function useLocal
55

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


30
56 // useStaticLocal initializes static local variable x only the
57 // first time the function is called; value of x is saved
58 // between calls to this function
59 void useStaticLocal( void )
60 {
61 // initialized only first time useStaticLocal is called
62 static int x = 50;
63
64 cout << endl << "local static x is " << x
65 << " on entering useStaticLocal" << endl;
66 ++x;
67 cout << "local static x is " << x
68 << " on exiting useStaticLocal" << endl;
69
70 } // end function useStaticLocal
71
72 // useGlobal modifies global variable x during each call
73 void useGlobal( void )
74 {
75 cout << endl << "global x is " << x
76 << " on entering useGlobal" << endl;
77 x *= 10;
78 cout << "global x is " << x
79 << " on exiting useGlobal" << endl;
80
81 } // end function useGlobal

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


31
local x in main's outer scope is 5
local x in main's inner scope is 7
local x in main's outer scope is 5

local x is 25 on entering useLocal


local x is 26 on exiting useLocal

local static x is 50 on entering


useStaticLocal
local static x is 51 on exiting useStaticLocal

global x is 1 on entering useGlobal


global x is 10 on exiting useGlobal
local x is 25 on entering useLocal
local x is 26 on exiting useLocal

local static x is 51 on entering


useStaticLocal
local static x is 52 on exiting useStaticLocal

global x is 10 on entering useGlobal


global x is 100 on exiting useGlobal

local x in main is 5

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


32

References and Reference Parameters

• Call by value
– Copy of data passed to function
– Changes to copy do not change original
– Prevent unwanted side effects
• Call by reference
– Function can directly access data
– Changes affect original

 2003 Prentice Hall, Inc. All rights reserved.


33

References and Reference Parameters

• Reference parameter
– Alias for argument in function call
• Passes parameter by reference
– Use & after data type in prototype
• void myFunction( int &data )
• Read “data is a reference to an int”
– Function call format the same
• However, original can now be changed

 2003 Prentice Hall, Inc. All rights reserved.


34
1 // Fig. 3.20: fig03_20.cpp
2 // Comparing pass-by-value and pass-by-reference
Outline
3 // with references.
4 #include <iostream>
fig03_20.cpp
5
6 using std::cout;
(1 of 2)
Notice the & operator,
7 using std::endl;
8 indicating pass-by-reference.
9 int squareByValue( int ); // function prototype
10 void squareByReference( int & ); // function prototype
11
12 int main()
13 {
14 int x = 2;
15 int z = 4;
16
17 // demonstrate squareByValue
18 cout << "x = " << x << " before squareByValue\n";
19 cout << "Value returned by squareByValue: "
20 << squareByValue( x ) << endl;
21 cout << "x = " << x << " after squareByValue\n" << endl;
22

 2003 Prentice Hall, Inc.


All rights reserved.
35
23 // demonstrate squareByReference
24 cout << "z = " << z << " before squareByReference" << endl;
Outline
25 squareByReference( z );
26 cout << "z = " << z << " after squareByReference" << endl;
fig03_20.cpp
27
28 return 0; // indicates successful termination
(2 of 2)
29 } // end main
Changes number, but
30
31 //
original parameter (x) is not
squareByValue multiplies number by itself, stores the
32 // modified.
result in number and returns the new value of number
33 int squareByValue( int number )
34 {
35 return number *= number; // caller's argument not modified
36
37 } // end function squareByValue
38 Changes numberRef, an
39 // squareByReference multiplies numberRef by itself and
alias for the original
40 // stores the result in the variable to which numberRef
parameter. Thus, z is
41 // refers in function main
42 void squareByReference( int &numberRef )
changed.
43 {
44 numberRef *= numberRef; // caller's argument modified
45
46 } // end function squareByReference

 2003 Prentice Hall, Inc.


All rights reserved.
36
x = 2 before squareByValue
Value returned by squareByValue: 4
Outline
x = 2 after squareByValue

fig03_20.cpp
z = 4 before squareByReference
z = 16 after squareByReference
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
37

References and Reference Parameters

• Pointers (chapter 5)
– Another way to pass-by-refernce
• References as aliases to other variables
– Refer to same variable
– Can be used within a function
int count = 1; // declare integer variable count
Int &cRef = count; // create cRef as an alias for count
++cRef; // increment count (using its alias)

• References must be initialized when declared


– Otherwise, compiler error
– Reference to undefined variable: reference to a variable
declared in a function, variable is discarded when function
terminates

 2003 Prentice Hall, Inc. All rights reserved.


38
1 // Fig. 3.21: fig03_21.cpp
2 // References must be initialized.
Outline
3 #include <iostream>
4
fig03_21.cpp
5 using std::cout;
6 using std::endl;
(1 of 1)
7
8 int main() fig03_21.cpp
9 { output (1 of 1)
10 int x = 3; y declared as a reference to x.
11
12 // y refers to (is an alias for) x
13 int &y = x;
14
15 cout << "x = " << x << endl << "y = " << y << endl;
16 y = 7;
17 cout << "x = " << x << endl << "y = " << y << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main

x = 3
y = 3
x = 7
y = 7

 2003 Prentice Hall, Inc.


All rights reserved.
39
1 // Fig. 3.22: fig03_22.cpp
2 // References must be initialized.
Outline
3 #include <iostream>
4
fig03_22.cpp
5 using std::cout;
6 using std::endl;
(1 of 1)
7
8 int main() Uninitialized reference – fig03_22.cpp
9 { compiler error. output (1 of 1)
10 int x = 3;
11 int &y; // Error: y must be initialized
12
13 cout << "x = " << x << endl << "y = " << y << endl;
14 y = 7;
15 cout << "x = " << x << endl << "y = " << y << endl;
16
17 return 0; // indicates successful termination
18
19 } // end main

Borland C++ command-line compiler error message:


Error E2304 Fig03_22.cpp 11: Reference variable 'y' must be
initialized in function main()

Microsoft Visual C++ compiler error message:


D:\cpphtp4_examples\ch03\Fig03_22.cpp(11) : error C2530: 'y' :
references must be initialized

 2003 Prentice Hall, Inc.


All rights reserved.
40

Default Arguments

• Function call with omitted parameters


– If not enough parameters, rightmost go to their defaults
– Default values
• Can be constants, global variables, or function calls
• Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
– myFunction(3)
• x = 3, y and z get defaults (rightmost)
– myFunction(3, 5)
• x = 3, y = 5 and z gets default

 2003 Prentice Hall, Inc. All rights reserved.


41
1 // Fig. 3.23: fig03_23.cpp
2 // Using default arguments.
Outline
3 #include <iostream>
4
5 using std::cout;
Set defaults in function fig03_23.cpp
6 using std::endl;
7
prototype. (1 of 2)
8 // function prototype that specifies default arguments
9 int boxVolume( int length = 1, int width = 1, int height = 1 );
10
11 int main()
12 {
13 // no arguments--use default values for all dimensions Function calls with some
14 cout << "The default box volume is: " << boxVolume(); parameters missing – the
15 rightmost parameters get their
16 // specify length; default width and height defaults.
17 cout << "\n\nThe volume of a box with length 10,\n"
18 << "width 1 and height 1 is: " << boxVolume( 10 );
19
20 // specify length and width; default height
21 cout << "\n\nThe volume of a box with length 10,\n"
22 << "width 5 and height 1 is: " << boxVolume( 10, 5 );
23

 2003 Prentice Hall, Inc.


All rights reserved.
42
24 // specify all arguments
25 cout << "\n\nThe volume of a box with length 10,\n"
Outline
26 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )
27 << endl;
fig03_23.cpp
28
29 return 0; // indicates successful termination
(2 of 2)
30
31 } // end main fig03_23.cpp
32 output (1 of 1)
33 // function boxVolume calculates the volume of a box
34 int boxVolume( int length, int width, int height )
35 {
36 return length * width * height;
37
38 } // end function boxVolume

The default box volume is: 1

The volume of a box with length 10,


width 1 and height 1 is: 10

The volume of a box with length 10,


width 5 and height 1 is: 50

The volume of a box with length 10,


width 5 and height 2 is: 100

 2003 Prentice Hall, Inc.


All rights reserved.
43

Function Overloading

• Function overloading
– Functions with same name and different parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }

• Overloaded functions distinguished by signature


– Based on name and parameter types (order matters)
– Name mangling
• Encodes function identifier with parameters
– Type-safe linkage
• Ensures proper overloaded function called

 2003 Prentice Hall, Inc. All rights reserved.


44
1 // Fig. 3.25: fig03_25.cpp
2 // Using overloaded functions.
Outline
3 #include <iostream>
4
fig03_25.cpp
5 using std::cout;
Overloaded functions have (1 of 2)
6 using std::endl;
7
the same name, but the
8 // function square for int values different parameters
9 int square( int x ) distinguish them.
10 {
11 cout << "Called square with int argument: " << x << endl;
12 return x * x;
13
14 } // end int version of function square
15
16 // function square for double values
17 double square( double y )
18 {
19 cout << "Called square with double argument: " << y << endl;
20 return y * y;
21
22 } // end double version of function square
23

 2003 Prentice Hall, Inc.


All rights reserved.
45
24 int main()
25 {
Outline
26 int intResult = square( 7 ); // calls int version
27 double doubleResult = square( 7.5 ); // calls double version
fig03_25.cpp
28
29 cout << "\nThe square of integer 7 is " << intResult
(2 of 2)
30
The proper function is called
<< "\nThe square of double 7.5 is " << doubleResult
31 << endl; based upon the argument fig03_25.cpp
32 (int or double). output (1 of 1)
33 return 0; // indicates successful termination
34
35 } // end main

Called square with int argument: 7


Called square with double argument: 7.5

The square of integer 7 is 49


The square of double 7.5 is 56.25

 2003 Prentice Hall, Inc.


All rights reserved.
46

Recursion

• Recursive functions
– Functions that call themselves
– Can only solve a base case
• If not base case
– Break problem into smaller problem(s)
– Launch new copy of function to work on the smaller
problem (recursive call/recursive step)
• Slowly converges towards base case
• Function makes call to itself inside the return statement
– Eventually base case gets solved
• Answer works way back up, solves entire problem

 2003 Prentice Hall, Inc. All rights reserved.


47

Recursion

• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
– Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
– Base case (1! = 0! = 1)

 2003 Prentice Hall, Inc. All rights reserved.


48
#include <iostream>
using namespace std;
Outline
int factorial(int number);

fig03_14.cpp
int main()
(1 of 2)
{
int x,y;
cin >> x;
y = factorial(x);
cout << "factorial " << x << " is " << y << endl;

return 0;
}

int factorial(int number)


{
cout << "Function call for number = " << number << endl;
if ( number <= 1 )
return 1;
// recursive step
else
return number * factorial( number - 1 );
}
4
Function call for number = 4
Function call for number = 3
Function call for number = 2
Function call for number = 1
Factorial 4 is : 24  2003 Prentice Hall, Inc.
All rights reserved.
49

Example Using Recursion: Fibonacci Series

• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...


– Each number sum of two previous ones
– Example of a recursive formula:
• fib(n) = fib(n-1) + fib(n-2)
• C++ code for Fibonacci function
long fibonacci( long n )
{
if ( n == 0 || n == 1 ) // base case
return n;
else
return fibonacci( n - 1 ) +
fibonacci( n – 2 );
}

 2003 Prentice Hall, Inc. All rights reserved.


50

Example Using Recursion: Fibonacci Series

f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0

 2003 Prentice Hall, Inc. All rights reserved.


51

Example Using Recursion: Fibonacci Series

• Order of operations
– return fibonacci( n - 1 ) + fibonacci( n - 2 );

• Do not know which one executed first


– C++ does not specify
– Only &&, || and ?: guaranteed left-to-right evaluation
• Recursive function calls
– Each level of recursion doubles the number of function calls
• 30th number = 2^30 ~ 4 billion function calls
– Exponential complexity

 2003 Prentice Hall, Inc. All rights reserved.


52
1 // Fig. 3.15: fig03_15.cpp
2 // Recursive fibonacci function.
Outline
3 #include <iostream>
4
fig03_15.cpp
5 using std::cout;
The Fibonacci numbers get (1 of 2)
6 using std::cin;
large very quickly, and are all
7 using std::endl;
8
non-negative integers. Thus,
9 unsigned long fibonacci( unsigned long ); //
we use the unsigned
function prototype
10 long data type.
11 int main()
12 {
13 unsigned long result, number;
14
15 // obtain integer from user
16 cout << "Enter an integer: ";
17 cin >> number;
18
19 // calculate fibonacci value for number input by user
20 result = fibonacci( number );
21
22 // display result
23 cout << "Fibonacci(" << number << ") = " << result << endl;
24
25 return 0; // indicates successful termination

 2003 Prentice Hall, Inc.


All rights reserved.
53
26
27 } // end main
Outline
28
29 // recursive definition of function fibonacci
fig03_15.cpp
30 unsigned long fibonacci( unsigned long n )
31 {
(2 of 2)
32 // base case
33 if ( n == 0 || n == 1 ) fig03_15.cpp
34 return n; output (1 of 2)
35
36 // recursive step
37 else
38 return fibonacci( n - 1 ) + fibonacci( n - 2 );
39
40 } // end function fibonacci

Enter an integer: 0
Fibonacci(0) = 0

Enter an integer: 1
Fibonacci(1) = 1

Enter an integer: 2
Fibonacci(2) = 1

Enter an integer: 3
Fibonacci(3) = 2

 2003 Prentice Hall, Inc.


All rights reserved.
54
Enter an integer: 4
Fibonacci(4) = 3
Outline

Enter an integer: 5
fig03_15.cpp
Fibonacci(5) = 5
output (2 of 2)
Enter an integer: 6
Fibonacci(6) = 8

Enter an integer: 10
Fibonacci(10) = 55

Enter an integer: 20
Fibonacci(20) = 6765

Enter an integer: 30
Fibonacci(30) = 832040

Enter an integer: 35
Fibonacci(35) = 9227465

 2003 Prentice Hall, Inc.


All rights reserved.
55

Recursion vs. Iteration

• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance between performance (iteration) and good
software engineering (recursion)

 2003 Prentice Hall, Inc. All rights reserved.


56

Recursion vs. Iteration (Assignment)

• Assignment:
– Rewrite the fibonacci series program without using recursion
(using iterations):

• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...


– Each number sum of two previous ones
– Example of a recursive formula:
• fib(n) = fib(n-1) + fib(n-2)

 2003 Prentice Hall, Inc. All rights reserved.


Outline

Intro to Programming

Chapter 4:
Arrays

Dr. Mohammad A. Alzubaidi

Yarmouk University
Computer Engineering Dept.

 2003 Prentice Hall, Inc.


All rights reserved.
2

Introduction

• Arrays
– Structures of related data items
– Static entity (same size throughout program)

 2003 Prentice Hall, Inc. All rights reserved.


3

Arrays

• Array
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
• To refer to an element
– Specify array name and position number (index)
– Format: arrayname[ position number ]
– First element at position 0
• N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1

 2003 Prentice Hall, Inc. All rights reserved.


4

Arrays

• Array elements like other variables


– Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
• Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]

 2003 Prentice Hall, Inc. All rights reserved.


5

Arrays
Name of array (Note
that all elements of
this array have the
same name, c)

c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78

Position number of the


element within array c

 2003 Prentice Hall, Inc. All rights reserved.


6

Declaring Arrays

• When declaring arrays, specify


– Name
– Type of array
• Any data type
– Number of elements
– type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats

• Declaring multiple arrays of same type


– Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];

 2003 Prentice Hall, Inc. All rights reserved.


7

Examples Using Arrays

• Initializing arrays
– For loop
• Set each element
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
• If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array

 2003 Prentice Hall, Inc. All rights reserved.


8
1 // Fig. 4.3: fig04_03.cpp
2 // Initializing an array.
Outline
3 #include <iostream>
4
fig04_03.cpp
5 using std::cout;
6 using std::endl;
(1 of 2)
7
8 #include <iomanip>
9
10 using std::setw;
11 Declare a 10-element array of
12 int main() integers.
13 {
14 int n[ 10 ]; // n is an array of Initialize array
10 integers to 0 using a
15 for loop. Note that the array
16 // initialize elements of array nhas
to elements
0 n[0] to n[9].
17 for ( int i = 0; i < 10; i++ )
18 n[ i ] = 0; // set element at location i to 0
19
20 cout << "Element" << setw( 13 ) << "Value" << endl;
21
22 // output contents of array n in tabular format
23 for ( int j = 0; j < 10; j++ )
24 cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
25

 2003 Prentice Hall, Inc.


All rights reserved.
9
26 return 0; // indicates successful termination
27
Outline
28 } // end main

Element Value fig04_03.cpp


0 0 (2 of 2)
1 0
2 0 fig04_03.cpp
3 0 output (1 of 1)
4 0
5 0
6 0
7 0
8 0
9 0

 2003 Prentice Hall, Inc.


All rights reserved.
10
1 // Fig. 4.4: fig04_04.cpp
2 // Initializing an array with a declaration.
Outline
3 #include <iostream>
4
fig04_04.cpp
5 using std::cout;
6 using std::endl;
(1 of 1)
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main() Note the use of the initializer
13 { list.
14 // use initializer list to initialize array n
15 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
16
17 cout << "Element" << setw( 13 ) << "Value" << endl;
18
19 // output contents of array n in tabular format
20 for ( int i = 0; i < 10; i++ )
21 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
22
23 return 0; // indicates successful termination
24
25 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
11
Element Value
0 32
Outline
1 27
2 64
fig04_04.cpp
3 18
4 95
output (1 of 1)
5 14
6 90
7 70
8 60
9 37

 2003 Prentice Hall, Inc.


All rights reserved.
12

Examples Using Arrays

• Array size
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables

 2003 Prentice Hall, Inc. All rights reserved.


13
1 // Fig. 4.5: fig04_05.cpp
2 // Initialize array s to the even integers from 2 to 20.
Outline
3 #include <iostream>
4
fig04_05.cpp
5 using std::cout;
6 using std::endl;
(1 of 2)
7
8 #include <iomanip>
9
10 using std::setw;
11 Note use of const keyword.
12 int main()
Only const variables can
13 {
14
specify array sizes.
// constant variable can be used to specify array size
15 const int arraySize = 10;
16
The program becomes more
17 int s[ arraySize ]; // array s scalable when we set the array
has 10 elements
18 size using a const variable.
19 for ( int i = 0; i < arraySize; i++ ) // Wesetcan valuesarraySize,
thechange
20 s[ i ] = 2 + 2 * i; and all the loops will still
21 work (otherwise, we’d have to
22 cout << "Element" << setw( 13 ) << "Value"update
<< endl;
every loop in the
23
program).

 2003 Prentice Hall, Inc.


All rights reserved.
14
24 // output contents of array s in tabular format
25 for ( int j = 0; j < arraySize; j++ )
Outline
26 cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
27
fig04_05.cpp
28 return 0; // indicates successful termination
29
(2 of 2)
30 } // end main
fig04_05.cpp
Element Value output (1 of 1)
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20

 2003 Prentice Hall, Inc.


All rights reserved.
15
1 // Fig. 4.6: fig04_06.cpp
2 // Using a properly initialized constant variable.
Outline
3 #include <iostream>
4
fig04_06.cpp
5 using std::cout;
6 using std::endl;
(1 of 1)
7 Proper initialization of
8 int main() const variable. fig04_06.cpp
9 { output (1 of 1)
10 const int x = 7; // initialized constant variable
11
12 cout << "The value of constant variable x is: "
13 << x << endl;
14
15 return 0; // indicates successful termination
16
17 } // end main

The value of constant variable x is: 7

 2003 Prentice Hall, Inc.


All rights reserved.
16
1 // Fig. 4.7: fig04_07.cpp
2 // A const object must be initialized.
Outline
3 Uninitialized const results
4 int main() in a syntax error. Attempting
to modify the const is fig04_07.cpp
5 {
const int x; // Error: x must be initialized
(1 of 1)
6 another error.
7
8 x = 7; // Error: cannot modify a const variable fig04_07.cpp
9 output (1 of 1)
10 return 0; // indicates successful termination
11
12 } // end main

d:\cpphtp4_examples\ch04\Fig04_07.cpp(6) : error C2734: 'x' :


const object must be initialized if not extern
d:\cpphtp4_examples\ch04\Fig04_07.cpp(8) : error C2166:
l-value specifies const object

 2003 Prentice Hall, Inc.


All rights reserved.
17
1 // Fig. 4.8: fig04_08.cpp
2 // Compute the sum of the elements of the array.
Outline
3 #include <iostream>
4
fig04_08.cpp
5 using std::cout;
6 using std::endl;
(1 of 1)
7
8 int main() fig04_08.cpp
9 { output (1 of 1)
10 const int arraySize = 10;
11
12 int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
13
14 int total = 0;
15
16 // sum contents of array a
17 for ( int i = 0; i < arraySize; i++ )
18 total += a[ i ];
19
20 cout << "Total of array element values is " << total << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main

Total of array element values is 55

 2003 Prentice Hall, Inc.


All rights reserved.
18
1 // Fig. 4.9: fig04_09.cpp
2 // Histogram printing program.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 const int arraySize = 10;
15 int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
16
17 cout << "Element" << setw( 13 ) << "Value"
18 << setw( 17 ) << "Histogram" << endl;
19
20 // for each element of array n, output a bar in histogram
21 for ( int i = 0; i < arraySize; i++ ) {
22 cout << setw( 7 ) << i << setw( 13 )
23 << n[ i ] << setw( 9 );
24
25 for ( int j = 0; j < n[ i ]; j++ ) // print one bar
26 cout << '*';

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


19
27
28 cout << endl; // start next line of output
29
30 } // end outer for structure
31
32 return 0; // indicates successful termination
33
34 } // end main

Element Value Histogram


0 19 *******************
1 3 ***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


20

Examples Using Arrays

• Recall static storage (chapter 3)


– If static, local variables save values between function
calls
– Visible only in function body
– Can declare local arrays to be static
• Initialized to zero
static int array[3];
• If not static
– Created (and destroyed) in every function call

 2003 Prentice Hall, Inc. All rights reserved.


21
1 // Fig. 4.13: fig04_13.cpp
2 // Static arrays are initialized to zero.
Outline
3 #include <iostream>
4
fig04_13.cpp
5 using std::cout;
6 using std::endl;
(1 of 3)
7
8 void staticArrayInit( void ); // function prototype
9 void automaticArrayInit( void ); // function prototype
10
11 int main()
12 {
13 cout << "First call to each function:\n";
14 staticArrayInit();
15 automaticArrayInit();
16
17 cout << "\n\nSecond call to each function:\n";
18 staticArrayInit();
19 automaticArrayInit();
20 cout << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main
25

 2003 Prentice Hall, Inc.


All rights reserved.
22
26 // function to demonstrate a static local array
27 void staticArrayInit( void ) Static array, initialized to zero Outline
28 { on first function call.
29 // initializes elements to 0 first time function is called
fig04_13.cpp
30 static int array1[ 3 ];
31
(2 of 3)
32 cout << "\nValues on entering staticArrayInit:\n";
33
34 // output contents of array1
35 for ( int i = 0; i < 3; i++ )
36 cout << "array1[" << i << "] = " << array1[ i ] << " ";
37
Array data is changed; the
38 cout << "\nValues on exiting staticArrayInit:\n";
39
modified values stay.
40 // modify and output contents of array1
41 for ( int j = 0; j < 3; j++ )
42 cout << "array1[" << j << "] = "
43 << ( array1[ j ] += 5 ) << " ";
44
45 } // end function staticArrayInit
46

 2003 Prentice Hall, Inc.


All rights reserved.
23
47 // function to demonstrate an automatic local array
48 void automaticArrayInit( void ) Automatic array, recreated
Outline
49 { with every function call.
50 // initializes elements each time function is called
fig04_13.cpp
51 int array2[ 3 ] = { 1, 2, 3 };
52
(3 of 3)
53 cout << "\n\nValues on entering automaticArrayInit:\n";
54
55 // output contents of array2
56 for ( int i = 0; i < 3; i++ )
57 cout << "array2[" << i << "] = " << array2[ i ] << " ";
58
Although the array is
59 cout << "\nValues on exiting automaticArrayInit:\n";
60
changed, it will be destroyed
61 // modify and output contents of array2 when the function exits and
62 for ( int j = 0; j < 3; j++ ) the changes will be lost.
63 cout << "array2[" << j << "] = "
64 << ( array2[ j ] += 5 ) << " ";
65
66 } // end function automaticArrayInit

 2003 Prentice Hall, Inc.


All rights reserved.
24
First call to each function:
Outline
Values on entering staticArrayInit:
array1[0] = 0 array1[1] = 0 array1[2] = 0
fig04_13.cpp
Values on exiting staticArrayInit:
array1[0] = 5 array1[1] = 5 array1[2] = 5
output (1 of 1)

Values on entering automaticArrayInit:


array2[0] = 1 array2[1] = 2 array2[2] = 3
Values on exiting automaticArrayInit:
array2[0] = 6 array2[1] = 7 array2[2] = 8

Second call to each function:

Values on entering staticArrayInit:


array1[0] = 5 array1[1] = 5 array1[2] = 5
Values on exiting staticArrayInit:
array1[0] = 10 array1[1] = 10 array1[2] = 10

Values on entering automaticArrayInit:


array2[0] = 1 array2[1] = 2 array2[2] = 3
Values on exiting automaticArrayInit:
array2[0] = 6 array2[1] = 7 array2[2] = 8

 2003 Prentice Hall, Inc.


All rights reserved.
25

Passing Arrays to Functions

• Specify name without brackets


– To pass array myArray to myFunction
int myArray[ 24 ];
myFunction( myArray, 24 );
– Array size usually passed, but not required
• Useful to iterate over all elements

 2003 Prentice Hall, Inc. All rights reserved.


26

Passing Arrays to Functions

• Arrays passed-by-reference
– Functions can modify original array data
– Value of name of array is address of first element
• Function knows where the array is stored
• Can change original memory locations
• Individual array elements passed-by-value
– Like regular variables
– square( myArray[3] );

 2003 Prentice Hall, Inc. All rights reserved.


27

Passing Arrays to Functions

• Functions taking arrays


– Function prototype
• void modifyArray( int b[], int arraySize );
• void modifyArray( int [], int );
– Names optional in prototype
• Both take an integer array and a single integer
– No need for array size between brackets
• Ignored by compiler
– If declare array parameter as const
• Cannot be modified (compiler error)
• void doNotModify( const int [] );

 2003 Prentice Hall, Inc. All rights reserved.


28
1 // Fig. 4.14: fig04_14.cpp
2 // Passing arrays and individual array elements to functions.
Outline
3 #include <iostream>
4
fig04_14.cpp
5 using std::cout;
6 using std::endl;
(1 of 3)
7
8 #include <iomanip>
9
Syntax for accepting an array
10 using std::setw; in parameter list.
11
12 void modifyArray( int [], int ); // appears strange
13 void modifyElement( int );
14
15 int main()
16 {
17 const int arraySize = 5; // size of array a
18 int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a
19
20 cout << "Effects of passing entire array by reference:"
21 << "\n\nThe values of the original array are:\n";
22
23 // output original array
24 for ( int i = 0; i < arraySize; i++ )
25 cout << setw( 3 ) << a[ i ];

 2003 Prentice Hall, Inc.


All rights reserved.
29
26
27 cout << endl;
Pass array name (a) and size Outline
28 to function. Arrays are
29 // pass array a to modifyArray bypassed-by-reference.
reference
fig04_14.cpp
30 modifyArray( a, arraySize );
31
(2 of 3)
32 cout << "The values of the modified array are:\n";
33
34 // output modified array
35 for ( int j = 0; j < arraySize; j++ )
36 cout << setw( 3 ) << a[ j ];
37
38 // output value of a[ 3 ]
39 cout << "\n\n\n"
40 << "Effects of passing array element by value:"
41
Pass a single array element
<< "\n\nThe value of a[3] is " << a[ 3 ] << '\n';
by
42 value; the original cannot be
43 // pass array element a[ 3 ] by modified.
value
44 modifyElement( a[ 3 ] );
45
46 // output value of a[ 3 ]
47 cout << "The value of a[3] is " << a[ 3 ] << endl;
48
49 return 0; // indicates successful termination
50
51 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
30
52 Although named b, the array
53 // in function modifyArray, "b" points to
Outline
points to the original array a.
54 // the original array "a" in memory
It can modify a’s data.
55 void modifyArray( int b[], int sizeOfArray )
fig04_14.cpp
56 {
57 // multiply each array element by 2
(3 of 3)
58 for ( int k = 0; k < sizeOfArray; k++ )
59 b[ k ] *= 2;
60
61 } // end function modifyArray
62 Individual array elements are
63 // passed
in function modifyElement, "e" is a local copybyof
value, and the
64 // array element a[ 3 ] passed from main originals cannot be changed.
65 void modifyElement( int e )
66 {
67 // multiply parameter by 2
68 cout << "Value in modifyElement is "
69 << ( e *= 2 ) << endl;
70
71 } // end function modifyElement

 2003 Prentice Hall, Inc.


All rights reserved.
31
Effects of passing entire array by reference:
Outline
The values of the original array are:
0 1 2 3 4
fig04_14.cpp
The values of the modified array are:
0 2 4 6 8
output (1 of 1)

Effects of passing array element by value:

The value of a[3] is 6


Value in modifyElement is 12
The value of a[3] is 6

 2003 Prentice Hall, Inc.


All rights reserved.
32
1 // Fig. 4.15: fig04_15.cpp
2 // Demonstrating the const type qualifier.
Outline
3 #include <iostream>
4
Array parameter declared as fig04_15.cpp
5 using std::cout;
const. Array cannot be (1 of 2)
6 using std::endl;
7 modified, even though it is
8 void tryToModifyArray( const int [] ); // passed byprototype
function reference.
9
10 int main()
11 {
12 int a[] = { 10, 20, 30 };
13
14 tryToModifyArray( a );
15
16 cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << '\n';
17
18 return 0; // indicates successful termination
19
20 } // end main
21

 2003 Prentice Hall, Inc.


All rights reserved.
33
22 // In function tryToModifyArray, "b" cannot be used
23 // to modify the original array "a" in main.
Outline
24 void tryToModifyArray( const int b[] )
25 {
fig04_15.cpp
26 b[ 0 ] /= 2; // error
27 b[ 1 ] /= 2; // error
(2 of 2)
28 b[ 2 ] /= 2; // error
29 fig04_15.cpp
30 } // end function tryToModifyArray output (1 of 1)

d:\cpphtp4_examples\ch04\Fig04_15.cpp(26) : error C2166:


l-value specifies const object
d:\cpphtp4_examples\ch04\Fig04_15.cpp(27) : error C2166:
l-value specifies const object
d:\cpphtp4_examples\ch04\Fig04_15.cpp(28) : error C2166:
l-value specifies const object

 2003 Prentice Hall, Inc.


All rights reserved.
34

Sorting Arrays

• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Massive amounts must be sorted
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical), no change
• If decreasing order, elements exchanged
– Repeat these steps for every element

 2003 Prentice Hall, Inc. All rights reserved.


35

Sorting Arrays

• Example:
– Go left to right, and exchange elements as necessary
• One pass for each element
– Original: 3 4 2 7 6
– Pass 1: 3 2 4 6 7 (elements exchanged)
– Pass 2: 2 3 4 6 7
– Pass 3: 2 3 4 6 7 (no changes needed)
– Pass 4: 2 3 4 6 7
– Pass 5: 2 3 4 6 7
– Small elements "bubble" to the top (like 2 in this example)

 2003 Prentice Hall, Inc. All rights reserved.


36

Sorting Arrays

• Swapping variables
int x = 3, y = 4;
y = x;
x = y;

• What happened?
– Both x and y are 3!
– Need a temporary variable
• Solution
int x = 3, y = 4, temp = 0;
temp = x; // temp gets 3
x = y; // x gets 4
y = temp; // y gets 3

 2003 Prentice Hall, Inc. All rights reserved.


37
1 // Fig. 4.16: fig04_16.cpp
2 // This program sorts an array's values into ascending order.
Outline
3 #include <iostream>
4
fig04_16.cpp
5 using std::cout;
6 using std::endl;
(1 of 3)
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 const int arraySize = 10; // size of array a
15 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
16 int hold; // temporary location used to swap array elements
17
18 cout << "Data items in original order\n";
19
20 // output original array
21 for ( int i = 0; i < arraySize; i++ )
22 cout << setw( 4 ) << a[ i ];
23

 2003 Prentice Hall, Inc.


All rights reserved.
38
24 // bubble sort Do a pass for each element in
25 // loop to control number of passes the array.
Outline
26 for ( int pass = 0; pass < arraySize - 1; pass++ )
27
fig04_16.cpp
28 // loop to control number of comparisons per pass
29 for ( int j = 0; j < arraySize - 1; j++ )
(2 of 3)
30
31 // compare side-by-side elements and swap them ifelement on the left
If the
32 // first element is greater than second element
(index j) is larger than the
33 if ( a[ j ] > a[ j + 1 ] ) {
element on the right (index j
34 hold = a[ j ];
35 a[ j ] = a[ j + 1 ];
+ 1), then we swap them.
36 a[ j + 1 ] = hold; Remember the need of a temp
37 variable.
38 } // end if
39

 2003 Prentice Hall, Inc.


All rights reserved.
39
40 cout << "\nData items in ascending order\n";
41
Outline
42 // output sorted array
43 for ( int k = 0; k < arraySize; k++ )
fig04_16.cpp
44 cout << setw( 4 ) << a[ k ];
45
(3 of 3)
46 cout << endl;
47 fig04_16.cpp
48 return 0; // indicates successful termination output (1 of 1)
49
50 } // end main

Data items in original order


2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89

 2003 Prentice Hall, Inc.


All rights reserved.
40
Case Study: Computing Mean and Median
Using Arrays
• Mean
– Average (sum/number of elements)
• Median
– Number in middle of sorted list
– 1, 2, 3, 4, 5 (3 is median)
– If even number of elements, take average of middle two

 2003 Prentice Hall, Inc. All rights reserved.


41
1 // Fig. 4.17: fig04_17.cpp
2 // This program introduces the topic of survey data analysis.
Outline
3 // It computes the mean and median of the data.
4 #include <iostream>
fig04_17.cpp
5
6 using std::cout;
(1 of 8)
7 using std::endl;
8 using std::fixed;
9 using std::showpoint;
10
11 #include <iomanip>
12
13 using std::setw;
14 using std::setprecision;
15
16 void mean( const int [], int );
17 void median( int [], int );
19 void bubbleSort( int[], int );
20 void printArray( const int[], int );
21
22 int main()
23 {
24 const int responseSize = 99; // size of array responses
25

 2003 Prentice Hall, Inc.


All rights reserved.
42
26 int frequency[ 10 ] = { 0 }; // initialize array frequency
27
Outline
28 // initialize array responses
29 int response[ responseSize ] =
fig04_17.cpp
30 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9,
31 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,
(2 of 8)
32 6, 7, 8, 9, 3, 9, 8, 7, 8, 7,
33 7, 8, 9, 8, 9, 8, 9, 7, 8, 9,
34 6, 7, 8, 7, 8, 7, 9, 8, 9, 2,
35 7, 8, 9, 8, 9, 8, 9, 7, 5, 3,
36 5, 6, 7, 2, 5, 3, 9, 4, 6, 4,
37 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
38 7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
39 4, 5, 6, 1, 6, 5, 7, 8, 7 };
40
41 // process responses
42 mean( response, responseSize );
43 median( response, responseSize );
45
46 return 0; // indicates successful termination
47
48 } // end main
49

 2003 Prentice Hall, Inc.


All rights reserved.
43
50 // calculate average of all response values
51 void mean( const int answer[], int arraySize )
Outline
52 {
53 int total = 0;
fig04_17.cpp
54
55 cout << "********\n Mean\n********\n";
(3 of 8)
56
57 // total response values
58 for ( int i = 0; i < arraySize; i++ )
59 total += answer[ i ];
60
61 // format and output results
62 cout << fixed << setprecision( 4 );
63
64 cout << "The mean is the average value of the data\n"
65 << "items. The mean is equal to the total of\n"
66 << "all the data items divided by the number\n"
67 << "of data items (" << arraySize We cast to a double to get
68 << "). The mean value for\nthis run is: " decimal points for the average
69 << total << " / " << arraySize << " = " (instead of an integer).
70 << static_cast< double >( total ) / arraySize
71 << "\n\n";
72
73 } // end function mean
74

 2003 Prentice Hall, Inc.


All rights reserved.
44
75 // sort array and determine median element's value
76 void median( int answer[], int size )
Outline
77 {
78 cout << "\n********\n Median\n********\n"
fig04_17.cpp
79 << "The unsorted array of responses is";
Sort array by passing it to a (4 of 8)
80
81 printArray( answer, size ); //
function. This keeps the
output unsorted array
82 program modular.
83 bubbleSort( answer, size ); // sort array
84
85 cout << "\n\nThe sorted array is";
86 printArray( answer, size ); // output sorted array
87
88 // display median element
89 cout << "\n\nThe median is element " << size / 2
90 << " of\nthe sorted " << size
91 << " element array.\nFor this run the median is "
92 << answer[ size / 2 ] << "\n\n";
93
94 } // end function median
95

 2003 Prentice Hall, Inc.


All rights reserved.
45
144
145 // function that sorts an array with bubble sort algorithm
Outline
146 void bubbleSort( int a[], int size )
147 {
fig04_17.cpp
148 int hold; // temporary location used to swap elements
149
(7 of 8)
150 // loop to control number of passes
151 for ( int pass = 1; pass < size; pass++ )
152
153 // loop to control number of comparisons per pass
154 for ( int j = 0; j < size - 1; j++ )
155
156 // swap elements if out of order
157 if ( a[ j ] > a[ j + 1 ] ) {
158 hold = a[ j ];
159 a[ j ] = a[ j + 1 ];
160 a[ j + 1 ] = hold;
161
162 } // end if
163
164 } // end function bubbleSort
165

 2003 Prentice Hall, Inc.


All rights reserved.
46
166 // output array contents (20 values per row)
167 void printArray( const int a[], int size )
Outline
168 {
169 for ( int i = 0; i < size; i++ ) {
fig04_17.cpp
170
171 if ( i % 20 == 0 ) // begin new line every 20 values
(8 of 8)
172 cout << endl;
173
174 cout << setw( 2 ) << a[ i ];
175
176 } // end for
177
178 } // end function printArray

 2003 Prentice Hall, Inc.


All rights reserved.
47
********
Mean
Outline
********
The mean is the average value of the data
fig04_17.cpp
items. The mean is equal to the total of
all the data items divided by the number
output (1 of 2)
of data items (99). The mean value for
this run is: 681 / 99 = 6.8788
********
Median
********
The unsorted array of responses is
6 7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7

The sorted array is


1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5
5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

The median is element 49 of


the sorted 99 element array.
For this run the median is 7
 2003 Prentice Hall, Inc.
All rights reserved.
48

Searching Arrays

• Search array for a key value


• Linear search
– Compare each element of array with key value
• Start at one end, go to other
– Useful for small and unsorted arrays
• Inefficient
• If search key not present, examines every element

 2003 Prentice Hall, Inc. All rights reserved.


49
1 // Fig. 4.19: fig04_19.cpp
2 // Linear search of an array.
Outline
3 #include <iostream>
4
fig04_19.cpp
5 using std::cout;
Takes array, search key, and (1 of 2)
6 using std::cin;
7 using std::endl;
array size.
8
9 int linearSearch( const int [], int, int ); // prototype
10
11 int main()
12 {
13 const int arraySize = 100; // size of array a
14 int a[ arraySize ]; // create array a
15 int searchKey; // value to locate in a
16
17 for ( int i = 0; i < arraySize; i++ ) // create some data
18 a[ i ] = 2 * i;
19
20 cout << "Enter integer search key: ";
21 cin >> searchKey;
22
23 // attempt to locate searchKey in array a
24 int element = linearSearch( a, searchKey, arraySize );
25

 2003 Prentice Hall, Inc.


All rights reserved.
50
26 // display results
27 if ( element != -1 )
Outline
28 cout << "Found value in element " << element << endl;
29 else
fig04_19.cpp
30 cout << "Value not found" << endl;
31
(2 of 2)
32 return 0; // indicates successful termination
33
34 } // end main
35
36 // compare key to every element of array until location is
37 // found or until end of array is reached; return subscript of
38 // element if key or -1 if key not found
39 int linearSearch( const int array[], int key, int sizeOfArray )
40 {
41 for ( int j = 0; j < sizeOfArray; j++ )
42
43 if ( array[ j ] == key ) // if found,
44 return j; // return location of key
45
46 return -1; // key not found
47
48 } // end function linearSearch

 2003 Prentice Hall, Inc.


All rights reserved.
51
Enter integer search key: 36
Found value in element 18
Outline

Enter integer search key: 37


fig04_19.cpp
Value not found
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
52

Strings

• Strings
– Arrays of characters
– All strings end with null ('\0')
– Examples
• char string1[] = "hello";
– Null character implicitly added
– string1 has 6 elements
• char string1[] = { 'h', 'e', 'l', 'l',
'o', '\0’ };
– Subscripting is the same
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'

 2003 Prentice Hall, Inc. All rights reserved.


53

Strings

• Input from keyboard


char string2[ 10 ];
cin >> string2;
– Puts user input in string
• Stops at first whitespace character
• Adds null character
– If too much text entered, data written beyond array
• We want to avoid this (section 5.12 explains how)
• Printing strings
– cout << string2 << endl;
• Does not work for other array types
– Characters printed until null found

 2003 Prentice Hall, Inc. All rights reserved.


54
1 // Fig. 4_12: fig04_12.cpp
2 // Treating character arrays as strings.
Outline
3 #include <iostream>
4
fig04_12.cpp
5 using std::cout;
6 using std::cin;
(1 of 2)
7 using std::endl;
8 Two different ways to declare
9 int main() strings. string2 is
10 { initialized, and its size
11 char string1[ 20 ], // determined
reserves 20 characters .
automatically
12 char string2[] = "string literal"; // reserves 15 characters
13 Examples of reading strings
14 // read string fromstring2
from user into array the keyboard and
15 cout << "Enter the string \"helloprinting them
there\": ";out.
16 cin >> string1; // reads "hello" [space terminates input]
17
18 // output strings
19 cout << "string1 is: " << string1
20 << "\nstring2 is: " << string2;
21
22 cout << "\nstring1 with spaces between characters is:\n";
23

 2003 Prentice Hall, Inc.


All rights reserved.
55
24 // output characters until null character is reached
25 for ( int i = 0; string1[ i ] != '\0'; i++ )
Outline
26 cout << string1[ i ] << ' ';
27
Can access the characters in a fig04_12.cpp
28 cin >> string1; // reads "there"
string using array notation. (2 of 2)
29 cout << "\nstring1 is: " << string1 << endl;
30
The loop ends when the null
31 return 0; // indicates successful character is found.
termination fig04_12.cpp
32 output (1 of 1)
33 } // end main

Enter the string "hello there": hello there


string1 is: hello
string2 is: string literal
string1 with spaces between characters is:
h e l l o
string1 is: there

 2003 Prentice Hall, Inc.


All rights reserved.
56

Multiple-Subscripted Arrays

• Multiple subscripts
– a[ i ][ j ]
– Tables with rows and columns
– Specify row, then column
– “Array of arrays”
• a[0] is an array of 4 elements
• a[0][0] is the first element of that array
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]

Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]

Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript

Array name
Row subscript

 2003 Prentice Hall, Inc. All rights reserved.


57

Multiple-Subscripted Arrays

• To initialize
– Default of 0
– Initializers grouped by row in braces 1 2
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 3 4
Row 0 Row 1

1 0
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 3 4

 2003 Prentice Hall, Inc. All rights reserved.


58

Multiple-Subscripted Arrays

• Referenced like normal


cout << b[ 0 ][ 1 ]; 1 0

– Outputs 0 3 4

– Cannot reference using commas


cout << b[ 0, 1 ];
• Syntax error
• Function prototypes
– Must specify sizes of subscripts
• First subscript not necessary, as with single-scripted arrays
– void printArray( int [][ 3 ] );

 2003 Prentice Hall, Inc. All rights reserved.


59
1 // Fig. 4.22: fig04_22.cpp
2 // Initializing multidimensional arrays.
Outline
3 #include <iostream>
4 Note the format of the fig04_22.cpp
5 using std::cout; prototype.
6 using std::endl;
(1 of 2)
7 Note the various initialization
8 void printArray( int [][ 3 ] );
styles. The elements in
9
array2 are assigned to the
10 int main()
11 {
first row and then the second.
12 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
13 int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
14 int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
15
16 cout << "Values in array1 by row are:" << endl;
17 printArray( array1 );
18
19 cout << "Values in array2 by row are:" << endl;
20 printArray( array2 );
21
22 cout << "Values in array3 by row are:" << endl;
23 printArray( array3 );
24
25 return 0; // indicates successful termination
26
27 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
60
28
29
For loops are often used to
// function to output array with two rows and three columns
Outline
30 void printArray( int a[][ 3 ] ) iterate through arrays. Nested
31 { loops are helpful with
fig04_22.cpp
32 for ( int i = 0; i < 2; i++ ) { multiple-subscripted
// for each row arrays.
33
(2 of 2)
34 for ( int j = 0; j < 3; j++ ) // output column values
35 cout << a[ i ][ j ] << ' '; fig04_22.cpp
36 output (1 of 1)
37 cout << endl; // start new line of output
38
39 } // end outer for structure
40
41 } // end function printArray

Values in array1 by row are:


1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0

 2003 Prentice Hall, Inc.


All rights reserved.
61

Multiple-Subscripted Arrays

• Next: program showing initialization


– After, program to keep track of students grades
– Multiple-subscripted array (table)
– Rows are students
– Columns are grades Quiz1 Quiz2

Student0 95 85
Student1 89 80

 2003 Prentice Hall, Inc. All rights reserved.


62
1 // Fig. 4.23: fig04_23.cpp
2 // Double-subscripted array example.
Outline
3 #include <iostream>
4
fig04_23.cpp
5 using std::cout;
6 using std::endl;
(1 of 6)
7 using std::fixed;
8 using std::left;
9
10 #include <iomanip>
11
12 using std::setw;
13 using std::setprecision;
14
15 const int students = 3; // number of students
16 const int exams = 4; // number of exams
17
18 // function prototypes
19 int minimum( int [][ exams ], int, int );
20 int maximum( int [][ exams ], int, int );
21 double average( int [], int );
22 void printArray( int [][ exams ], int, int );
23

 2003 Prentice Hall, Inc.


All rights reserved.
63
24 int main()
25 {
Outline
26 // initialize student grades for three students (rows)
27 int studentGrades[ students ][ exams ] =
fig04_23.cpp
28 { { 77, 68, 86, 73 },
29 { 96, 87, 89, 78 },
(2 of 6)
30 { 70, 90, 86, 81 } };
31
32 // output array studentGrades
33 cout << "The array is:\n";
34 printArray( studentGrades, students, exams );
35
36 // determine smallest and largest grade values
37 cout << "\n\nLowest grade: "
38 << minimum( studentGrades, students, exams )
39 << "\nHighest grade: "
40 << maximum( studentGrades, students, exams ) << '\n';
41
42 cout << fixed << setprecision( 2 );
43

 2003 Prentice Hall, Inc.


All rights reserved.
64
44 // calculate average grade for each student
45 for ( int person = 0; person < students; person++ )
Outline
46 cout << "The average grade for student " << person
47 << " is "
fig04_23.cpp
48 << average( studentGrades[ person ], exams )
49 << endl;
(3 of 6)
50 Determines the average for
51 return 0; // indicates successful termination
one student. We pass the
52
array/row containing the
53 } // end main
54
student’s grades. Note that
55 // find minimum grade
studentGrades[0] is
56 int minimum( int grades[][ exams ], int itselfint
pupils, an array.
tests )
57 {
58 int lowGrade = 100; // initialize to highest possible grade
59
60 for ( int i = 0; i < pupils; i++ )
61
62 for ( int j = 0; j < tests; j++ )
63
64 if ( grades[ i ][ j ] < lowGrade )
65 lowGrade = grades[ i ][ j ];
66
67 return lowGrade;
68
69 } // end function minimum

 2003 Prentice Hall, Inc.


All rights reserved.
65
70
71 // find maximum grade
Outline
72 int maximum( int grades[][ exams ], int pupils, int tests )
73 {
fig04_23.cpp
74 int highGrade = 0; // initialize to lowest possible grade
75
(4 of 6)
76 for ( int i = 0; i < pupils; i++ )
77
78 for ( int j = 0; j < tests; j++ )
79
80 if ( grades[ i ][ j ] > highGrade )
81 highGrade = grades[ i ][ j ];
82
83 return highGrade;
84
85 } // end function maximum
86

 2003 Prentice Hall, Inc.


All rights reserved.
66
87 // determine average grade for particular student
88 double average( int setOfGrades[], int tests )
Outline
89 {
90 int total = 0;
fig04_23.cpp
91
92 // total all grades for one student
(5 of 6)
93 for ( int i = 0; i < tests; i++ )
94 total += setOfGrades[ i ];
95
96 return static_cast< double >( total ) / tests; // average
97
98 } // end function maximum

 2003 Prentice Hall, Inc.


All rights reserved.
67
99
100 // Print the array
Outline
101 void printArray( int grades[][ exams ], int pupils, int tests )
102 {
fig04_23.cpp
103 // set left justification and output column heads
104 cout << left << " [0] [1] [2] [3]";
(6 of 6)
105
106 // output grades in tabular format
107 for ( int i = 0; i < pupils; i++ ) {
108
109 // output label for row
110 cout << "\nstudentGrades[" << i << "] ";
111
112 // output one grades for one student
113 for ( int j = 0; j < tests; j++ )
114 cout << setw( 5 ) << grades[ i ][ j ];
115
116 } // end outer for
117
118 } // end function printArray

 2003 Prentice Hall, Inc.


All rights reserved.
68
The array is:
[0] [1] [2] [3]
Outline
studentGrades[0] 77 68 86 73
studentGrades[1] 96 87 89 78
fig04_23.cpp
studentGrades[2] 70 90 86 81
output (1 of 1)
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75

 2003 Prentice Hall, Inc.


All rights reserved.
Intro to Programming

Chapter 5:
Pointers and Strings

Dr. Mohammad A. Alzubaidi

Yarmouk University
Computer Engineering Dept.

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


2

Introduction

• Pointers
– Powerful, but difficult to master
– Simulate pass-by-reference
– Close relationship with arrays and strings

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


3
Pointer Variable Declarations and
Initialization
• Pointer variables
– Contain memory addresses as values count
– Normally, variable contains specific value (direct reference) 7
– Pointers contain address of variable that has specific value (indirect
reference)
• Indirection countPtr count

– Referencing value through pointer 7

• Pointer declarations
– * indicates variable is pointer
int *myPtr;
declares pointer to int, pointer of type int *
– Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
• Can declare pointers to any data type
• Pointer initialization
– Initialized to 0, NULL, or address
• 0 or NULL points to nothing

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


4

Pointer Operators

• & (address operator)


– Returns memory address of its operand
– Example
int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y
– yPtr “points to” y

y yptr y
5 500000 600000 600000 5
yPtr

address of y
is value of
yptr

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


5

Pointer Operators

• * (indirection/dereferencing operator)
– Returns synonym for object its pointer operand points to
– *yPtr returns y (because yPtr points to y).
– dereferenced pointer is lvalue
*yptr = 9; // assigns 9 to y
• * and & are inverses of each other

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


6
1 // Fig. 5.4: fig05_04.cpp The address of a is 0012FED4
2 // Using the & and * operators. The value of aPtr is 0012FED4
3 #include <iostream>
4 The value of a is 7
5 using std::cout; The value of *aPtr is 7
6 using std::endl;
7 Showing that * and & are inverses of each other.
8 int main() &*aPtr = 0012FED4
9 { *&aPtr = 0012FED4
10 int a; // a is an integer
11 int *aPtr; // aPtr is a pointer to an integer
12
13 a = 7;
14 aPtr = &a; // aPtr assigned address of a
15
16 cout << "The address of a is " << &a
17 << "\nThe value of aPtr is " << aPtr;
18
19 cout << "\n\nThe value of a is " << a
20 << "\nThe value of *aPtr is " << *aPtr;
21
22 cout << "\n\nShowing that * and & are inverses of "
23 << "each other.\n&*aPtr = " << &*aPtr
24 << "\n*&aPtr = " << *&aPtr << endl;
25
26 return 0; // indicates successful termination
27
28 } // end main

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


7

Calling Functions by Reference


• 3 ways to pass arguments to function
– Pass-by-value
– Pass-by-reference with reference arguments
– Pass-by-reference with pointer arguments
• Return: can return one value from function
• Arguments passed to function using reference arguments
– Modify original values of arguments
– More than one value “returned”
• Pass-by-reference with pointer arguments
– Simulate pass-by-reference
• Use pointers and indirection operator
– Pass address of argument using & operator
– Arrays not passed with & because array name already pointer
– * operator used as alias/nickname for variable inside of function

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


8
1 // Fig. 5.6: fig05_06.cpp
2 // Cube a variable using pass-by-value.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int cubeByValue( int ); // prototype
9
10 int main()
11 {
12 int number = 5;
13
14 cout << "The original value of number is " << number;
15
16 // pass number by value to cubeByValue
17 number = cubeByValue( number );
18
19 cout << "\nThe new value of number is " << number << endl;
20
21 return 0; // indicates successful termination
22
23 } // end main
24
The original value of number is 5
// calculate and return cube of integer argument
The new value of number is 125
26 int cubeByValue( int n )
27 {
28 return n * n * n; // cube local variable n and return result
29
30 } // end function cubeByValue
 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com
9
1 // Fig. 5.7: fig05_07.cpp
2 // Cube a variable using pass-by-reference
3 // with a pointer argument.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 void cubeByReference( int * ); // prototype
10
11 int main()
12 {
13 int number = 5;
14
15 cout << "The original value of number is " << number;
16
17 // pass address of number to cubeByReference
18 cubeByReference( &number );
19
20 cout << "\nThe new value of number is " << number << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main
25 // calculate cube of *nPtr; modifies variable number in main
27 void cubeByReference( int *nPtr )
28 {
The original value of number is 5
29 *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr
The new value of number is 125
30
31 } // end function cubeByReference
 2003 Prentice Hall, Inc.
All rights reserved. http://www.deitel.com
10

Using const with Pointers

• const qualifier
– Value of variable should not be modified
– const used when function does not need to change a variable
• Principle of least privilege
– Award function enough access to accomplish task, but no more
• Four ways to pass pointer to function
– Nonconstant pointer to nonconstant data
• Highest amount of access
– Nonconstant pointer to constant data
– Constant pointer to nonconstant data
– Constant pointer to constant data
• Least amount of access

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


11
1 // Fig. 5.10: fig05_10.cpp
2 // Converting lowercase letters to uppercase letters
3 // using a non-constant pointer to non-constant data.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 #include <cctype> // prototypes for islower and toupper
10
11 void convertToUppercase( char * );
12
13 int main()
14 {
15 char phrase[] = "characters and $32.98";
16
17 cout << "The phrase before conversion is: " << phrase;
18 convertToUppercase( phrase );
19 cout << "\nThe phrase after conversion is: "
20 << phrase << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main
25

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


12
26 // convert string to uppercase letters
27 void convertToUppercase( char *sPtr )
28 {
29 while ( *sPtr != '\0' ) { // current character is not '\0'
30
31 if ( islower( *sPtr ) ) // if character is lowercase,
32 *sPtr = toupper( *sPtr ); // convert to uppercase
33
34 ++sPtr; // move sPtr to next character in string
35
36 } // end while
37
38 } // end function convertToUppercase

The phrase before conversion is: characters and $32.98


The phrase after conversion is: CHARACTERS AND $32.98

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


13
1 // Fig. 5.11: fig05_11.cpp
2 // Printing a string one character at a time using
3 // a non-constant pointer to constant data.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8 9 void printCharacters( const char * );
10
11 int main()
12 {
13 char phrase[] = "print characters of a string";
14 15 cout << "The string is:\n";
16 printCharacters( phrase );
17 cout << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main
22
// sPtr cannot modify the character to which it points,
24 // i.e., sPtr is a "read-only" pointer
25 void printCharacters( const char *sPtr )
26 {
27 for ( ; *sPtr != '\0'; sPtr++ ) // no initialization
28 cout << *sPtr;
29 The string is:
30 } // end function printCharacters print characters of a string

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


14
1 // Fig. 5.12: fig05_12.cpp
2 // Attempting to modify data through a
3 // non-constant pointer to constant data.
4
5 void f( const int * ); // prototype
6
7 int main()
8 {
9 int y;
10
11 f( &y ); // f attempts illegal modification
12
13 return 0; // indicates successful termination
14
15 } // end main
16
17 // xPtr cannot modify the value of the variable
18 // to which it points
19 void f( const int *xPtr )
20 {
21 *xPtr = 100; // error: cannot modify a const object
22
23 } // end function f

d:\cpphtp4_examples\ch05\Fig05_12.cpp(21) : error C2166:


l-value specifies const object

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


15
Using const with Pointers
const pointers
Always point to same memory location- Default for array name - Must be initialized
when declared
1 // Fig. 5.13: fig05_13.cpp
2 // Attempting to modify a constant pointer to
3 // non-constant data.
4
5 int main()
6 {
7 int x, y;
8
9 // ptr is a constant pointer to an integer that can
10 // be modified through ptr, but ptr always points to the
11 // same memory location.
12 int * const ptr = &x;
13
14 *ptr = 7; // allowed: *ptr is not const
15 ptr = &y; // error: ptr is const; cannot assign new address
16
17 return 0; // indicates successful termination
18
19 } // end main

d:\cpphtp4_examples\ch05\Fig05_13.cpp(15) : error C2166:


l-value specifies const object

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


16
1 // Fig. 5.14: fig05_14.cpp
2 // Attempting to modify a constant pointer to constant data.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 int x = 5, y;
11
12 // ptr is a constant pointer to a constant integer.
13 // ptr always points to the same location; the integer
14 // at that location cannot be modified.
15 const int *const ptr = &x;
16
17 cout << *ptr << endl;
18
19 *ptr = 7; // error: *ptr is const; cannot assign new value
20 ptr = &y; // error: ptr is const; cannot assign new address
21
22 return 0; // indicates successful termination
23
24 } // end main
d:\cpphtp4_examples\ch05\Fig05_14.cpp(19) : error C2166:
l-value specifies const object
d:\cpphtp4_examples\ch05\Fig05_14.cpp(20) : error C2166:
l-value specifies const object

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


17

Bubble Sort Using Pass-by-Reference


• Implement bubbleSort using pointers
– Want function swap to access array elements
• Individual array elements: scalars
– Passed by value by default
• Pass by reference using address operator &
• sizeof
– Unary operator returns size of operand in bytes
– For arrays, sizeof returns
( size of 1 element ) * ( number of elements )
– If sizeof( int ) = 4, then
int myArray[10];
cout << sizeof(myArray);
will print 40
• sizeof can be used with
– Variable names
– Type names
– Constant values

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


18
1 // Fig. 5.15: fig05_15.cpp
2 // This program puts values into an array, sorts the values into
3 // ascending order, and prints the resulting array.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 #include <iomanip>
10
11 using std::setw;
12
13 void bubbleSort( int *, const int ); // prototype
14 void swap( int * const, int * const ); // prototype
15
16 int main()
17 {
18 const int arraySize = 10;
19 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
20
21 cout << "Data items in original order\n";
22 23 for ( int i = 0; i < arraySize; i++ )
24 cout << setw( 4 ) << a[ i ];
25 bubbleSort( a, arraySize ); // sort the array
27
28 cout << "\nData items in ascending order\n";
29
30 for ( int j = 0; j < arraySize; j++ )
31 cout << setw( 4 ) << a[ j ];

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


19
32
33 cout << endl;
34
35 return 0; // indicates successful termination
36
37 } // end main
38 39 // sort an array of integers using bubble sort algorithm
40 void bubbleSort( int *array, const int size )
41 {
42 // loop to control passes
43 for ( int pass = 0; pass < size - 1; pass++ )
44
45 // loop to control comparisons during each pass
46 for ( int k = 0; k < size - 1; k++ )
47
48 // swap adjacent elements if they are out of order
49 if ( array[ k ] > array[ k + 1 ] )
50 swap( &array[ k ], &array[ k + 1 ] ); Data items in original order
51 2 6 4 8 10 12 89 68 45 37
52 } // end function bubbleSort Data items in ascending order
53 2 4 6 8 10 12 37 45 68 89
54 // swap values at memory locations to which
55 // element1Ptr and element2Ptr point
56 void swap( int * const element1Ptr, int * const element2Ptr )
57 {
58 int hold = *element1Ptr;
59 *element1Ptr = *element2Ptr;
60 *element2Ptr = hold;
61 62 } // end function swap

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


20
1 // Fig. 5.16: fig05_16.cpp
2 // Sizeof operator when used on an array name
3 // returns the number of bytes in the array.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 size_t getSize( double * ); // prototype
10
11 int main()
12 {
13 double array[ 20 ];
14
15 cout << "The number of bytes in the array is "
16 << sizeof( array );
17
18 cout << "\nThe number of bytes returned by getSize is "
19 << getSize( array ) << endl;
20
21 return 0; // indicates successful termination
22 23 } // end main
24
25 // return size of ptr
26 size_t getSize( double *ptr )
27 {
28 return sizeof( ptr );
29 The number of bytes in the array is 160
30 } // end function getSize The number of bytes returned by getSize is 4

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


21
1 // Fig. 5.17: fig05_17.cpp
2 // Demonstrating the sizeof operator.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 char c;
11 short s;
12 int i;
13 long l;
14 float f;
15 double d;
16 long double ld;
17 int array[ 20 ];
18 int *ptr = array;
19

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


22
20 cout << "sizeof c = " << sizeof c
21 << "\tsizeof(char) = " << sizeof( char )
22 << "\nsizeof s = " << sizeof s
23 << "\tsizeof(short) = " << sizeof( short )
24 << "\nsizeof i = " << sizeof i
25 << "\tsizeof(int) = " << sizeof( int )
26 << "\nsizeof l = " << sizeof l
27 << "\tsizeof(long) = " << sizeof( long )
28 << "\nsizeof f = " << sizeof f
29 << "\tsizeof(float) = " << sizeof( float )
30 << "\nsizeof d = " << sizeof d
31 << "\tsizeof(double) = " << sizeof( double )
32 << "\nsizeof ld = " << sizeof ld
33 << "\tsizeof(long double) = " << sizeof( long double )
34 << "\nsizeof array = " << sizeof array
35 << "\nsizeof ptr = " << sizeof ptr
36 << endl;
37
38 return 0; // indicates successful termination
39
40 } // end main sizeof c = 1 sizeof(char) = 1
sizeof s = 2 sizeof(short) = 2
sizeof i = 4 sizeof(int) = 4
sizeof l = 4 sizeof(long) = 4
sizeof f = 4 sizeof(float) = 4
sizeof d = 8 sizeof(double) = 8
sizeof ld = 8 sizeof(long double) = 8
sizeof array = 80
sizeof ptr = 4

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


23

Pointer Expressions and Pointer Arithmetic

• Pointer arithmetic
– Increment/decrement pointer (++ or --)
– Add/subtract an integer to/from a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
– Pointer arithmetic meaningless unless performed on pointer to
array
• 5 element int array on a machine using 4 byte ints
– vPtr points to first element v[ 0 ], which is at location 3000
vPtr = 3000 location
3000 3004 3008 3012 3016

– vPtr += 2; sets vPtr to 3008


v[0] v[1] v[2] v[3] v[4]
vPtr points to v[ 2 ]

pointer variable vPtr

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


24

Pointer Expressions and Pointer Arithmetic

• Subtracting pointers
– Returns number of elements between two addresses
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
vPtr2 - vPtr == 2

• Pointer assignment
– Pointer can be assigned to another pointer if both of same type
– If not same type, cast operator must be used
– Exception: pointer to void (type void *)
• Generic pointer, represents any type
• No casting needed to convert pointer to void pointer
• void pointers cannot be dereferenced

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


25

Pointer Expressions and Pointer Arithmetic

• Pointer comparison
– Use equality and relational operators
– Comparisons meaningless unless pointers point to members
of same array
– Compare addresses stored in pointers
– Example: could show that one pointer points to higher
numbered element of array than other pointer
– Common use to determine whether pointer is 0 (does not
point to anything)

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


26

Relationship Between Pointers and Arrays

• Arrays and pointers closely related


– Array name like constant pointer
– Pointers can do array subscripting operations
• Accessing array elements with pointers
– Element b[ n ] can be accessed by *( bPtr + n )
• Called pointer/offset notation
– Addresses
• &b[ 3 ] same as bPtr + 3
– Array name can be treated as pointer
• b[ 3 ] same as *( b + 3 )
– Pointers can be subscripted (pointer/subscript notation)
• bPtr[ 3 ] same as b[ 3 ]

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


27
1 // Fig. 5.20: fig05_20.cpp
2 // Using subscripting and pointer notations with arrays.
3
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 int main()
10 {
11 int b[] = { 10, 20, 30, 40 };
12 int *bPtr = b; // set bPtr to point to array b
13
14 // output array b using array subscript notation
15 cout << "Array b printed with:\n"
16 << "Array subscript notation\n";
17
18 for ( int i = 0; i < 4; i++ )
19 cout << "b[" << i << "] = " << b[ i ] << '\n';
20
21 // output array b using the array name and
22 // pointer/offset notation
23 cout << "\nPointer/offset notation where "
24 << "the pointer is the array name\n";
25

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


28
26 for ( int offset1 = 0; offset1 < 4; offset1++ )
27 cout << "*(b + " << offset1 << ") = "
28 << *( b + offset1 ) << '\n';
29
30 // output array b using bPtr and array subscript notation Array b printed with:
31 cout << "\nPointer subscript notation\n";
32 Array subscript notation
33 for ( int j = 0; j < 4; j++ ) b[0] = 10
34 cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n'; b[1] = 20
35 b[2] = 30
36 cout << "\nPointer/offset notation\n"; b[3] = 40
37
38 // output array b using bPtr and pointer/offset notation Pointer/offset notation…………
39 for ( int offset2 = 0; offset2 < 4; offset2++ ) *(b + 0) = 10
40 cout << "*(bPtr + " << offset2 << ") = " *(b + 1) = 20
41 << *( bPtr + offset2 ) << '\n'; *(b + 2) = 30
42 *(b + 3) = 40
43 return 0; // indicates successful termination
44 Pointer subscript notation
45 } // end main bPtr[0] = 10
bPtr[1] = 20
bPtr[2] = 30
bPtr[3] = 40

Pointer/offset notation
*(bPtr + 0) = 10
*(bPtr + 1) = 20
*(bPtr + 2) = 30
*(bPtr + 3) = 40

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


29
1 // Fig. 5.21: fig05_21.cpp
2 // Copying a string using array notation
3 // and pointer notation.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 void copy1( char *, const char * ); // prototype
10 void copy2( char *, const char * ); // prototype
11
12 int main()
13 {
14 char string1[ 10 ];
15 char *string2 = "Hello";
16 char string3[ 10 ];
17 char string4[] = "Good Bye";
18
19 copy1( string1, string2 );
20 cout << "string1 = " << string1 << endl;
21
22 copy2( string3, string4 );
23 cout << "string3 = " << string3 << endl;
24
25 return 0; // indicates successful termination

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


30
26
27 } // end main
28
29 // copy s2 to s1 using array notation
30 void copy1( char *s1, const char *s2 )
31 {
32 for ( int i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ )
33 ; // do nothing in body
34
35 } // end function copy1
36
37 // copy s2 to s1 using pointer notation
38 void copy2( char *s1, const char *s2 )
39 {
40 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ )
41 ; // do nothing in body
42
43 } // end function copy2

string1 = Hello
string3 = Good Bye

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


31

Fundamentals of Characters and Strings

• Character constant
– Integer value represented as character in single quotes
– 'z' is integer value of z
• 122 in ASCII
• String
– Series of characters treated as single unit
– Can include letters, digits, special characters +, -, * ...
– String literal (string constants)
• Enclosed in double quotes, for example:
"I like C++"
– Array of characters, ends with null character '\0'
– String is constant pointer
• Pointer to string’s first character
– Like arrays
 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com
32

Fundamentals of Characters and Strings

• String assignment
– Character array
• char color[] = "blue";
– Creates 5 element char array color
• last element is '\0'
– Variable of type char *
• char *colorPtr = "blue";
– Creates pointer colorPtr to letter b in string “blue”
• “blue” somewhere in memory
– Alternative for character array
• char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘\0’ };

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


33

Fundamentals of Characters and Strings


• Reading strings
– Assign input to character array word[ 20 ]
cin >> word
• Reads characters until whitespace or EOF
• String could exceed array size
cin >> setw( 20 ) >> word;
• Reads 19 characters (space reserved for '\0')
• cin.getline
– Read line of text
– cin.getline( array, size, delimiter );
– Copies input into specified array until either
• One less than size is reached
• delimiter character is input
– Example
char sentence[ 80 ];
cin.getline( sentence, 80, '\n' );

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


34
String Manipulation Functions of the String-
handling Library
• String handling library <cstring> provides
functions to
– Manipulate string data
– Compare strings
– Search strings for characters and other strings
– Tokenize strings (separate strings into logical pieces)

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


35
String Manipulation Functions of the String-
handling Library
char *strcpy( char *s1, const Copies the string s2 into the character
char *s2 ); array s1. The value of s1 is returned.
char *strncpy( char *s1, const Copies at most n characters of the string s2
char *s2, size_t n ); into the character array s1. The value of s1 is
returned.
char *strcat( char *s1, const Appends the string s2 to the string s1. The
char *s2 ); first character of s2 overwrites the terminating
null character of s1. The value of s1 is
returned.
char *strncat( char *s1, const Appends at most n characters of string s2 to
char *s2, size_t n ); string s1. The first character of s2 overwrites
the terminating null character of s1. The value
of s1 is returned.

int strcmp( const char *s1, Compares the string s1 with the string s2. The
const char *s2 ); function returns a value of zero, less than zero
or greater than zero if s1 is equal to, less than
or greater than s2, respectively.

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


36
String Manipulation Functions of the String-
handling Library
int strncmp( const char *s1, const Compares up to n characters of the string
char *s2, size_t n ); s1 with the string s2. The function returns
zero, less than zero or greater than zero if
s1 is equal to, less than or greater than s2,
respectively.
char *strtok( char *s1, const char A sequence of calls to strtok breaks
*s2 ); string s1 into “tokens”—logical pieces
such as words in a line of text—delimited
by characters contained in string s2. The
first call contains s1 as the first argument,
and subsequent calls to continue tokenizing
the same string contain NULL as the first
argument. A pointer to the current token is
returned by each call. If there are no more
tokens when the function is called, NULL is
returned.
size_t strlen( const char *s ); Determines the length of string s. The
number of characters preceding the
terminating null character is returned.

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


37
String Manipulation Functions of the String-
handling Library
• Copying strings
– char *strcpy( char *s1, const char *s2 )
• Copies second argument into first argument
– First argument must be large enough to store string and
terminating null character
– char *strncpy( char *s1, const char *s2,
size_t n )
• Specifies number of characters to be copied from string into
array
• Does not necessarily copy terminating null character

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


38
1 // Fig. 5.28: fig05_28.cpp
2 // Using strcpy and strncpy. The string in array x is: Happy Birthday to You
3 #include <iostream> The string in array y is: Happy Birthday to You
4 The string in array z is: Happy Birthday
5 using std::cout;
6 using std::endl;
7
8 #include <cstring> // prototypes for strcpy and strncpy
9
10 int main()
11 {
12 char x[] = "Happy Birthday to You";
13 char y[ 25 ];
14 char z[ 15 ];
15
16 strcpy( y, x ); // copy contents of x into y
17
18 cout << "The string in array x is: " << x
19 << "\nThe string in array y is: " << y << '\n';
20
21 // copy first 14 characters of x into z
22 strncpy( z, x, 14 ); // does not copy null character
23 z[ 14 ] = '\0'; // append '\0' to z's contents
24
25 cout << "The string in array z is: " << z << endl;
26
27 return 0; // indicates successful termination
28
29 } // end main

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


39
String Manipulation Functions of the String-
handling Library
• Concatenating strings
– char *strcat( char *s1, const char *s2 )
• Appends second argument to first argument
• First character of second argument replaces null character
terminating first argument
• Ensure first argument large enough to store concatenated result
and null character
– char *strncat( char *s1, const char *s2,
size_t n )
• Appends specified number of characters from second argument
to first argument
• Appends terminating null character to result

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


40
1 // Fig. 5.29: fig05_29.cpp
2 // Using strcat and strncat.
3 #include <iostream>
4 5 using std::cout;
6 using std::endl;
7
8 #include <cstring> // prototypes for strcat and strncat s1 = Happy
9 s2 = New Year
10 int main()
11 { After strcat(s1, s2):
12 char s1[ 20 ] = "Happy "; s1 = Happy New Year
13 char s2[] = "New Year "; s2 = New Year
14 char s3[ 40 ] = "";
15 16 cout << "s1 = " << s1 << "\ns2 = " << s2; After strncat(s3, s1, 6):
17 s1 = Happy New Year
18 strcat( s1, s2 ); // concatenate s2 to s1 s3 = Happy
19 20 cout << "\n\nAfter strcat(s1, s2):\ns1 = " << s1
21 << "\ns2 = " << s2; After strcat(s3, s1):
22 s1 = Happy New Year
23 // concatenate first 6 characters of s1 to s3 s3 = Happy Happy New Year
24 strncat( s3, s1, 6 ); // places '\0' after last character
25 26 cout << "\n\nAfter strncat(s3, s1, 6):\ns1 = " << s1
27 << "\ns3 = " << s3;
28 29 strcat( s3, s1 ); // concatenate s1 to s3
30 cout << "\n\nAfter strcat(s3, s1):\ns1 = " << s1
31 << "\ns3 = " << s3 << endl;
32 33 return 0; // indicates successful termination
34
35 } // end main

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


41
String Manipulation Functions of the String-
handling Library
• Comparing strings
– Characters represented as numeric codes
• Strings compared using numeric codes
– Character codes / character sets
• ASCII
– “American Standard Code for Information Interchage”
• EBCDIC
– “Extended Binary Coded Decimal Interchange Code”

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


42
String Manipulation Functions of the String-
handling Library
• Comparing strings
– int strcmp( const char *s1, const char
*s2 )
• Compares character by character
• Returns
– Zero if strings equal
– Negative value if first string less than second string
– Positive value if first string greater than second string
– int strncmp( const char *s1,
const char *s2, size_t n )
• Compares up to specified number of characters
• Stops comparing if reaches null character in one of arguments

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


43
1 // Fig. 5.30: fig05_30.cpp
2 // Using strcmp and strncmp.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9 10 using std::setw;
11 12 #include <cstring> // prototypes for strcmp and strncmp
13
14 int main() s1 = Happy New Year
15 { s2 = Happy New Year
16 char *s1 = "Happy New Year"; s3 = Happy Holidays
17 char *s2 = "Happy New Year";
18 char *s3 = "Happy Holidays"; strcmp(s1, s2) = 0
19 20 cout << "s1 = " << s1 << "\ns2 = " << s2 strcmp(s1, s3) = 1
21 << "\ns3 = " << s3 << "\n\nstrcmp(s1, s2) = " strcmp(s3, s1) = -1
22 << setw( 2 ) << strcmp( s1, s2 )
23 << "\nstrcmp(s1, s3) = " << setw( 2 ) strncmp(s1, s3, 6) = 0
24 << strcmp( s1, s3 ) << "\nstrcmp(s3, s1) = " strncmp(s1, s3, 7) = 1
25 << setw( 2 ) << strcmp( s3, s1 ); strncmp(s3, s1, 7) = -1
26 27 cout << "\n\nstrncmp(s1, s3, 6) = " << setw( 2 )
28 << strncmp( s1, s3, 6 ) << "\nstrncmp(s1, s3, 7) = "
29 << setw( 2 ) << strncmp( s1, s3, 7 )
30 << "\nstrncmp(s3, s1, 7) = "
31 << setw( 2 ) << strncmp( s3, s1, 7 ) << endl;
32 33 return 0; // indicates successful termination
34 35 } // end main

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


44
String Manipulation Functions of the String-
handling Library
• Tokenizing
– Breaking strings into tokens, separated by delimiting characters
– Tokens usually logical units, such as words (separated by spaces)
– "This is my string" has 4 word tokens (separated by
spaces)
– char *strtok( char *s1, const char *s2 )
• Multiple calls required
– First call contains two arguments, string to be tokenized and
string containing delimiting characters
• Finds next delimiting character and replaces with null
character
– Subsequent calls continue tokenizing
• Call with first argument NULL
• Determining string lengths
– size_t strlen( const char *s )
• Returns number of characters in string
– Terminating null character not included in length

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


45
1 // Fig. 5.31: fig05_31.cpp
2 // Using strtok.
The string to be tokenized is:
3 #include <iostream>
This is a sentence with 7 tokens
4
5 using std::cout;
The tokens are:
6 using std::endl;
7
This
8 #include <cstring> // prototype for strtok
is
9
a
10 int main()
sentence
11 {
with
12 char sentence[] = "This is a sentence with 7 tokens";
7
13 char *tokenPtr;
tokens
14 15 cout << "The string to be tokenized is:\n" << sentence
16 << "\n\nThe tokens are:\n\n";
After strtok, sentence = This
17 18 // begin tokenization of sentence
19 tokenPtr = strtok( sentence, " " );
20 21 // continue tokenizing sentence until tokenPtr becomes NULL
22 while ( tokenPtr != NULL ) {
23 cout << tokenPtr << '\n';
24 tokenPtr = strtok( NULL, " " ); // get next token
25
26 } // end while
27
28 cout << "\nAfter strtok, sentence = " << sentence << endl;
29
30 return 0; // indicates successful termination
31 32 } // end main

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


46
1 // Fig. 5.32: fig05_32.cpp
2 // Using strlen.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <cstring> // prototype for strlen
9
10 int main()
11 {
12 char *string1 = "abcdefghijklmnopqrstuvwxyz";
13 char *string2 = "four";
14 char *string3 = "Boston";
15
16 cout << "The length of \"" << string1
17 << "\" is " << strlen( string1 )
18 << "\nThe length of \"" << string2
19 << "\" is " << strlen( string2 )
20 << "\nThe length of \"" << string3
21 << "\" is " << strlen( string3 ) << endl;
22
23 return 0; // indicates successful termination
24
25 } // end main
The length of "abcdefghijklmnopqrstuvwxyz" is 26
The length of "four" is 4
The length of "Boston" is 6

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


Intro to Programming

Chapter 6:
Classes and Data Abstraction

Dr. Mohammad A. Alzubaidi

Yarmouk University
Computer Engineering Dept.

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


2

Structure Definitions

• Structures
– Aggregate data types built using elements of other types

struct Time { Structure tag


int hour;
int minute; Structure members
int second;
};
• Structure member naming
– In same struct: must have unique names
– In different structs: can share name
• struct definition must end with semicolon

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


3

Structure Definitions

• struct definition
– Creates new data type used to declare variables
– Structure variables declared like variables of other types
– Examples:
• Time timeObject;
• Time timeArray[ 10 ];
• Time *timePtr = &timeobject;

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


4

Accessing Structure Members

• Member access operators


– Dot operator (.) for structure and class members
– Arrow operator (->) for structure and class members via
pointer to object
– Print member hour of timeObject:
cout << timeObject.hour;
OR
timePtr = &timeObject;
cout << timePtr->hour;
– timePtr->hour same as ( *timePtr ).hour
• Parentheses required
– * lower precedence than .

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


5
Implementing a User-Defined Type Time
with a struct
• Default: structures passed by value
– Pass structure by reference
• Avoid overhead of copying structure
• Also …
– Cannot print as unit
• Must print/format member by member
– Cannot compare as unit
• Must compare member by member

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


6
1 // Fig. 6.1: fig06_01.cpp
2 // Create a structure, set its members, and print it.
3 #include <iostream>
4 5 using std::cout;
6 using std::endl;
7 8 #include <iomanip>
9 10 using std::setfill;
11 using std::setw;
12 13 // structure definition
14 struct Time {
15 int hour; // 0-23 (24-hour clock format)
16 int minute; // 0-59
17 int second; // 0-59
18 19 }; // end struct Time
20 21 void printUniversal( const Time & ); // prototype
22 void printStandard( const Time & ); // prototype
23 24 int main()
25 {
26 Time dinnerTime; // variable of new type Time
27 28 dinnerTime.hour = 18; // set hour member of dinnerTime
29 dinnerTime.minute = 30; // set minute member of dinnerTime
30 dinnerTime.second = 0; // set second member of dinnerTime
31 32 cout << "Dinner will be held at ";
33 printUniversal( dinnerTime );
34 cout << " universal time,\nwhich is ";
35 printStandard( dinnerTime );
36 cout << " standard time.\n";
37

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


7
38 dinnerTime.hour = 29; // set hour to invalid value
39 dinnerTime.minute = 73; // set minute to invalid value
40
41 cout << "\nTime with invalid values: ";
42 printUniversal( dinnerTime );
43 cout << endl; Dinner will be held at 18:30:00 universal time,
44 which is 6:30:00 PM standard time.
45 return 0;
46 Time with invalid values: 29:73:00
47 } // end main
48 49 // print time in universal-time format
50 void printUniversal( const Time &t )
51 {
52 cout << setfill( '0' ) << setw( 2 ) << t.hour << ":"
53 << setw( 2 ) << t.minute << ":"
54 << setw( 2 ) << t.second;
55 56 } // end function printUniversal
57 58 // print time in standard-time format
59 void printStandard( const Time &t )
60 {
61 cout << ( ( t.hour == 0 || t.hour == 12 ) ?
62 12 : t.hour % 12 ) << ":" << setfill( '0' )
63 << setw( 2 ) << t.minute << ":"
64 << setw( 2 ) << t.second
65 << ( t.hour < 12 ? " AM" : " PM" );
66 67 } // end function printStandard

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


8
Implementing a Time Abstract Data Type
with a class
• Classes
– Model objects
• Attributes (data members)
• Behaviors (member functions)
– Defined using keyword class
– Member functions
• Methods
• Invoked in response to messages
• Member access specifiers
– public:
• Accessible wherever object of class in scope
– private:
• Accessible only to member functions of class

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


9
Implementing a Time Abstract Data Type
with a class
• Constructor function
– Special member function: Initializes data members , Same name
as class
– Called when object instantiated
– Several constructors: Function overloading
– No return type
1 class Time {
2
3 public:
4 Time(); // constructor
5 void setTime( int, int, int ); // set hour, minute, second
6 void printUniversal(); // print universal-time format
7 void printStandard(); // print standard-time format
8 9 private:
10 int hour; // 0 - 23 (24-hour clock format)
11 int minute; // 0 - 59
12 int second; // 0 - 59
13 14 }; // end class Time

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


10
Implementing a Time Abstract Data Type
with a class
• Objects of class
– After class definition
• Class name new type specified
– C++ extensible language
• Object, array, pointer and reference declarations
– Example:
Time sunset; // object of type Time
Time arrayOfTimes[ 5 ]; // array of Time objects
Time *pointerToTime; // pointer to a Time object
Time &dinnerTime = sunset; // reference to a Time object

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


11
Implementing a Time Abstract Data Type
with a class
• Member functions defined outside class
– Binary scope resolution operator (::)
• “Ties” member name to class name
• Uniquely identify functions of particular class
• Different classes can have member functions with same name
– Format for defining member functions
ReturnType ClassName::MemberFunctionName( )
{ … }
– Does not change whether function public or private
• Member functions defined inside class
– Do not need scope resolution operator, class name

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


12
1 // Fig. 6.3: fig06_03.cpp
2 // Time class.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setfill;
11 using std::setw;
12
13 // Time abstract data type (ADT) definition
14 class Time {
15
16 public:
17 Time(); // constructor
18 void setTime( int, int, int ); // set hour, minute, second
19 void printUniversal(); // print universal-time format
20 void printStandard(); // print standard-time format
21
22 private:
23 int hour; // 0 - 23 (24-hour clock format)
24 int minute; // 0 - 59
25 int second; // 0 - 59
26 27 }; // end class Time
28

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


13
29 // Time constructor initializes each data member to zero and
30 // ensures all Time objects start in a consistent state
31 Time::Time()
32 {
33 hour = minute = second = 0;
34
35 } // end Time constructor
36
37 // set new Time value using universal time, perform validity
38 // checks on the data values and set invalid values to zero
39 void Time::setTime( int h, int m, int s )
40 {
41 hour = ( h >= 0 && h < 24 ) ? h : 0;
42 minute = ( m >= 0 && m < 60 ) ? m : 0;
43 second = ( s >= 0 && s < 60 ) ? s : 0;
44
45 } // end function setTime
46

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


14
47 // print Time in universal format
48 void Time::printUniversal()
49 {
50 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
51 << setw( 2 ) << minute << ":"
52 << setw( 2 ) << second;
53
54 } // end function printUniversal
55
56 // print Time in standard format
57 void Time::printStandard()
58 {
59 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
60 << ":" << setfill( '0' ) << setw( 2 ) << minute
61 << ":" << setw( 2 ) << second
62 << ( hour < 12 ? " AM" : " PM" );
63
64 } // end function printStandard
65
66 int main()
67 {
68 Time t; // instantiate object t of class Time
69

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


15
70 // output Time object t's initial values
71 cout << "The initial universal time is ";
72 t.printUniversal(); // 00:00:00
73
74 cout << "\nThe initial standard time is "; The initial universal time is 00:00:00
75 t.printStandard(); // 12:00:00 AM The initial standard time is 12:00:00 AM
76
77 t.setTime( 13, 27, 6 ); // change time Universal time after setTime is 13:27:06
78 Standard time after setTime is 1:27:06 PM
79 // output Time object t's new values
80 cout << "\n\nUniversal time after setTime is "; After attempting invalid settings:
81 t.printUniversal(); // 13:27:06 Universal time: 00:00:00
82 Standard time: 12:00:00 AM
83 cout << "\nStandard time after setTime is ";
84 t.printStandard(); // 1:27:06 PM
85
86 t.setTime( 99, 99, 99 ); // attempt invalid settings
87
88 // output t's values after specifying invalid values
89 cout << "\n\nAfter attempting invalid settings:"
90 << "\nUniversal time: ";
91 t.printUniversal(); // 00:00:00
92 93 cout << "\nStandard time: ";
94 t.printStandard(); // 12:00:00 AM
95 cout << endl;
96 97 return 0;
98 99 } // end main

 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com


16
Implementing a Time Abstract Data Type
with a class
• Destructors
– Same name as class
• Preceded with tilde (~)
– No arguments
– Cannot be overloaded
– Performs “termination housekeeping”
• Advantages of using classes
– Simplify programming
– Interfaces
• Hide implementation
– Software reuse
• Composition (aggregation)
– Class objects included as members of other classes
• Inheritance
– New classes derived from old
 2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com

You might also like