0% found this document useful (0 votes)
140 views

Chapter 1: Introduction To Computers, Programs, and C++: Sections 1.1-1.3, 1.6-1.9

Uploaded by

Wael Abdulal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views

Chapter 1: Introduction To Computers, Programs, and C++: Sections 1.1-1.3, 1.6-1.9

Uploaded by

Wael Abdulal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 298

1/29/20

Chapter 1: Introduction to
Computers, Programs, and C++

Sections 1.1-1.3, 1.6-1.9

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline

• Introduction and Computers (§§1.1–1.2)


• Programming languages (§§1.3)
• A simple C++ program for console output (§1.6)
• C++ program-development cycle (§1.7)
• Programming style and documentation (§1.8)
• Programming errors (§1.9)

1
1/29/20

What is a Computer?
A computer consists of a CPU, memory, hard disk,
monitor, and communication devices.

Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices
e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,
and Tape and NIC Mouse Printer

CPU
The central processing unit (CPU) is the brain of a
computer. It retrieves instructions from memory and
executes them. The CPU speed is measured in megahertz
(MHz), with 1 megahertz equaling 1 million pulses per
second. The speed of the CPU has been improved
continuously. If you buy a PC now, you can get an Intel
Core i7 Processor at 3 gigahertz (1 gigahertz is 1000
megahertz).
Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices
e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,
and Tape and NIC Mouse Printer
4

2
1/29/20

Memory
Memory is to store data and program instructions for CPU
to execute. A memory unit is an ordered sequence of
bytes, each holds eight bits. A program and its data must
be brought to memory before they can be executed. A
memory byte is never empty, but its initial content may be
meaningless to your program. The current content of a
memory byte is lost whenever new information is placed
in it.
Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices
e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,
and Tape and NIC Mouse Printer
5

How Data is Stored?


• Data of various kinds are
encoded as a series of bits (zeros
and ones).
• The encoding scheme varies. For
example, character ‘J’ is
represented by 01001010 in one
byte.
• A small number such as 3 can be
stored in a single byte.
• If computer needs to store a
large number that cannot fit into
a single byte, it uses a number of
adjacent bytes.
• A byte is the minimum storage
unit.
6

3
1/29/20

Storage Devices
Memory is volatile, because information is lost when the
power is off. Programs and data are permanently stored
on storage devices and are moved to memory when the
computer actually uses them. There are four main types
of storage devices: Disk drives (hard disks), Solid-state
devices (SSD, Flash), CD drives (CD-R and CD-RW), and
Tape drives.
Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices
e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,
and Tape and NIC Mouse Printer

Outline

• Introduction and Computers (§§1.1–1.2)


• Programming languages (§§1.3)
• A simple C++ program for console output (§1.6)
• C++ program-development cycle (§1.7)
• Programming style and documentation (§1.8)
• Programming errors (§1.9)

4
1/29/20

Programs
Computer programs, known as software, are instructions
to the computer.

You tell a computer what to do through programs. Without


programs, a computer is an empty machine. Computers do
not understand human languages, so you need to use
computer languages to communicate with them.

Programs are written using programming languages.

Programming Languages
Machine Language Assembly Language High-Level Language
Machine language is a set of primitive instructions built
into every computer. The instructions are in the form of
binary code, so you have to enter binary codes for various
instructions. Program with native machine language is a
tedious process. Moreover the programs are highly
difficult to read and modify. For example, to add two
numbers, you might write an instruction in binary like this:

1101101010011010

10

10

5
1/29/20

Programming Languages
Machine Language Assembly Language High-Level Language
Assembly languages were developed to make
programming easy. Since the computer cannot understand
assembly language, however, a program called assembler
is used to convert assembly language programs into
machine code. For example, to add two numbers, you
might write an instruction in assembly code like this:
add 2, 3, result

11

11

Programming Languages
Machine Language Assembly Language High-Level Language

The high-level languages are English-like and easy to learn


and program. For example, the following is a high-level
language statement that computes the area of a circle with
radius 5:
area = 5 * 5 * 3.1416;

12

12

6
1/29/20

Popular High-Level Languages


• COBOL (COmmon Business Oriented Language)
• FORTRAN (FORmula TRANslation)
• BASIC (Beginner All-purpose Symbolic Instructional Code)
• Pascal (named for Blaise Pascal)
• Ada (named for Ada Lovelace)
• C (whose developer designed B first)
• Visual Basic (Basic-like visual language developed by Microsoft)
• Delphi (Pascal-like visual language developed by Borland)
• C++ (an object-oriented language, based on C)
• Java (a popular object-oriented language, similar to C++)
• C# (a Java-like developed my Microsoft)

13

13

Compiling Source Code


A program written in a high-level language is called a
source program. Since a computer cannot understand a
source program. Program called a compiler is used to
translate the source program into a machine language
program called an object program. The object program is
often then linked with other supporting library code
before the object can be executed on the machine.

Source File Compiler Object File Linker Excutable File

14

14

7
1/29/20

Compiling versus Interpretation


• Some programming languages like Python have
interpreters that translate and execute a program one
statement at a time (a).
• C++ needs a compiler that translates the entire source
program into a machine-language file for execution (b).

15

15

Outline

• Introduction and Computers (§§1.1–1.2)


• Programming languages (§§1.3)
• A simple C++ program for console output (§1.6)
• C++ program-development cycle (§1.7)
• Programming style and documentation (§1.8)
• Programming errors (§1.9)

16

16

8
1/29/20

A Simple C++ Program


Let us begin with a simple C++ program that displays the
message “Welcome to C++!” on the console.
#include <iostream>
using namespace std;
int main()
{
// Display Welcome to C++ to the console
cout << "Welcome to C++!" << endl;
return 0;
} Note: Clicking the green button displays the source code with
interactive animation and live run. Internet connection is needed for
this button.
Note: Clicking the blue button runs the code from Windows. To
Welcome
enable the buttons, you must download the entire slide file slide.zip
Run and unzip the files into a directory (e.g., c:\slide). If you are using
Office 2010 or higher, check PowerPoint2010.doc located in the
same folder with this ppt file. 17

17

Special Characters in C++

18

18

9
1/29/20

Comments in C++

19

19

Extending the Simple C++ Program


Once you understand the program, it is easy to extend it to
display more messages. For example, you can rewrite the
program to display three messages.
#include <iostream>
using namespace std;
int main()
{
cout << "Programming is fun!" << endl;
cout << "Fundamentals First" << endl;
cout << "Problem Driven" << endl;
return 0;
} Run
WelcomeWithThreeMessages

20

20

10
1/29/20

Computing with Numbers


Further, you can perform mathematical computations and
displays the result to the console. Listing 1.3 gives such an
example.
#include <iostream>
using namespace std;
int main()
{
cout << "(10.5 + 2 * 3) / (45 - 3.5) = ";
cout << (10.5 + 2 * 3) / (45 - 3.5) << endl;

return 0;
} ComputeExpression Run

21

21

Outline

• Introduction and Computers (§§1.1–1.2)


• Programming languages (§§1.3)
• A simple C++ program for console output (§1.6)
• C++ program-development cycle (§1.7)
• Programming style and documentation (§1.8)
• Programming errors (§1.9)

22

22

11
1/29/20

1. Creating and Compiling

23

23

2. Linking and Running Programs

24

24

12
1/29/20

C++ IDE Tutorial


You can develop a C++ program from a command window
or from an IDE. An IDE is software that provides an
integrated development environment (IDE) for rapidly
developing C++ programs. Editing, compiling, building,
debugging, and online help are integrated in one graphical
user interface. Just enter source code or open an existing
file in a window, then click a button, menu item, or
function key to compile and run the program. Examples of
popular IDEs are Microsoft Visual Studio, Dev-C++, Eclipse,
and NetBeans. All these IDEs can be downloaded free.

25

25

Outline

• Introduction and Computers (§§1.1–1.2)


• Programming languages (§§1.3)
• A simple C++ program for console output (§1.6)
• C++ program-development cycle (§1.7)
• Programming style and documentation (§1.8)
• Programming errors (§1.9)

26

26

13
1/29/20

Programming Style and Documentation

• Appropriate Comments
• Proper Indentation and Spacing Lines
• Block Styles
#include <iostream>
using namespace std;
int main()
{
cout << "(10.5 + 2 * 3) / (45 - 3.5) = ";
cout << (10.5 + 2 * 3) / (45 - 3.5) << endl;

return 0;
} 27

27

Outline

• Introduction and Computers (§§1.1–1.2)


• Programming languages (§§1.3)
• A simple C++ program for console output (§1.6)
• C++ program-development cycle (§1.7)
• Programming style and documentation (§1.8)
• Programming errors (§1.9)

28

28

14
1/29/20

Programming Errors

1. Syntax Errors
2. Runtime Errors
3. Logic Errors

29

29

Syntax Errors

ShowSyntaxErrors

30

30

15
1/29/20

Runtime Errors

ShowRuntimeErrors Run

31

31

Logic Errors

ShowLogicErrors Run

32

32

16
1/29/20

Common Errors

1. Missing Braces
2. Missing Semicolons
3. Missing Quotation Marks
4. Misspelling Names

33

33

Outline

• Introduction and Computers (§§1.1–1.2)


• Programming languages (§§1.3)
• A simple C++ program for console output (§1.6)
• C++ program-development cycle (§1.7)
• Programming style and documentation (§1.8)
• Programming errors (§1.9)

34

34

17
1/29/20

Chapter 2: Elementary
Programming

Sections 2.1-2.13, 2.15, 2.16

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 2

1
1/29/20

Writing a Simple Program


A program that computes the area of the circle.

Note: Clicking the green button displays the source code


with interactive animation. You can also run the code in
a browser. Internet connection is needed for this
button.
ComputeArea
Note: Clicking the blue button runs the code from
Windows. If you cannot run the buttons, see
Run IMPORTANT NOTE: If you cannot run the buttons, see
www.cs.armstrong.edu/liang/javaslidenote.doc.
3

animation

Trace the Program Execution


#include <iostream> allocate memory
using namespace std; for radius

int main() { radius no value


double radius;
double area;

// Step 1: Read in radius


radius = 20;

// Step 2: Compute area


area = radius * radius * 3.14159;

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
}

2
1/29/20

animation

Trace the Program Execution


#include <iostream> memory
using namespace std;
radius no value
int main() {
area no value
double radius;
double area;

// Step 1: Read in radius allocate memory


radius = 20; for area

// Step 2: Compute area


area = radius * radius * 3.14159;

// Step 3: Display the area


cout << "The area is ";
cout << area << std::endl;
}

animation

Trace the Program Execution


#include <iostream> assign 20 to radius
using namespace std;
radius 20
int main() {
double radius; area no value
double area;

// Step 1: Read in radius


radius = 20;

// Step 2: Compute area


area = radius * radius * 3.14159;

// Step 3: Display the area


cout << "The area is ";
cout << area << std::endl;
}

3
1/29/20

animation

Trace the Program Execution


#include <iostream>
memory
using namespace std;

int main() {
radius 20
double radius; area 1256.636
double area;

// Step 1: Read in radius


radius = 20; compute area and assign it
to variable area
// Step 2: Compute area
area = radius * radius * 3.14159;

// Step 3: Display the area


cout << "The area is ";
cout << area << std::endl;
}

animation

Trace the Program Execution


#include <iostream>
using namespace std; memory

int main() { radius 20


double radius; area 1256.636
double area;

// Step 1: Read in radius


radius = 20;
print a message to the
// Step 2: Compute area console
area = radius * radius * 3.14159;

// Step 3: Display the area


cout << "The area is ";
cout << area << std::endl;
}

4
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 9

Reading Input from the Keyboard

You can use the cin object to read input from the
keyboard.

ComputeAreaWithConsoleInput Run

10

10

5
1/29/20

Reading Multiple Input in One


Statement
#include <iostream>
using namespace std;

int main()
{
// Prompt the user to enter three numbers
double number1, number2, number3;
cout << "Enter three numbers: ";
cin >> number1 >> number2 >> number3;

// Compute average
double average = (number1 + number2 + number3) / 3;

// Display result
cout << "The average of " << number1 << " " << number2
<< " " << number3 << " is " << average << endl;

return 0;
} ComputeAverage Run
11

11

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 12

12

6
1/29/20

Identifiers
Identifiers are the names that identify elements such as
variables and functions in a program.
• An identifier is a sequence of characters that consists of
letters, digits, and underscores (_).
• An identifier must start with a letter or an underscore. It
cannot start with a digit.
• An identifier cannot be a reserved word. (See Appendix
A, “C++ Keywords,” for a list of reserved words.)
• An identifier can be of any length, but your C++
compiler may impose some restriction. Use identifiers of
31 characters or fewer to ensure portability.

13

13

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 14

14

7
1/29/20

Variables
Variables are used to represent values that may be
changed in the program.

// Compute the first area


radius = 1.0;
area = radius * radius * 3.14159;
cout << area;

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
cout << area;
15

15

Declaring Variables
datatype variable1, variable2,..., variablen;

int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;

16

16

8
1/29/20

Declaring Variables
int i, j, k; // Declare three integers

int i = 10; // Declare and initialize

int i(1), j(2); // Is equivalent to


int i = 1, j = 2;

17

17

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 18

18

9
1/29/20

Assignment Statements
An assignment statement designates a value for a variable. An
assignment statement can be used as an expression in C++.

x = 1; // Assign 1 to x;

y = x + 1; // Assign 2 to y;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;

19

19

Assignment Statements
An assignment statement designates a value for a variable.

i = j = k = 1; // Assigns 1 to the three


// variables

cout << x = 1; // Assigns 1 to x and


// outputs 1

20

20

10
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 21

21

Named Constants
A named constant is an identifier that represents a
permanent value.

const datatype CONSTANTNAME = VALUE;

const double PI = 3.14159;

ComputeAreaConstant Run

22

22

11
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 23

23

Numerical Data Types


• Signed integers
– 16 bits: short -3
– 32 bits: int 100000
– 64 bits: long long -2147483648
• Unsigned integers
– 16 bits: unsigned short 4
– 32 bits: unsigned
– 64 bits: unsigned long long

24

24

12
1/29/20

Synonymous Types

short int is synonymous to short. For example,


short int i = 2;
is same as
short i = 2;

unsigned short int ≡ unsigned short


unsigned int ≡ unsigned
long int ≡ long
unsigned long int ≡ unsigned long

25

25

Numerical Data Types

• Floating-point numbers
– 32 bits: float 1.5
– 64 bits: double -1.23456E+2
– 80 bits: long double 9.1e-1000

• When a number such as 50.534 is converted into


scientific notation such as 5.0534e+1, its decimal
point is moved (i.e., floated) to a new position.

26

26

13
1/29/20

double vs. float


The double type values are more accurate than the float
type values. For example,

cout << "1.0 / 3.0 is " << 1.0 / 3.0 << endl;

1.0 / 3.0 is 0.33333333333333331

16 digits

cout << "1.0F / 3.0F is " << 1.0F / 3.0F << endl;

1.0F / 3.0F is 0.3333333432674408


7 digits

27

27

Numerical Data Types


Name Synonymy Range Storage Size

short short int –215 to 215–1 (-32,768 to 32,767) 16-bit signed

unsigned short unsigned short int 0 to 216–1 (65535) 16-bit unsigned

int signed –231 to 231–1 (-2147483648 to 2147483647) 32-bit

unsigned unsigned int 0 to 232–1 (4294967295) 32-bit unsigned


signed
long long int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed
unsigned long unsigned long int 0 to 232–1 (4294967295) 32-bit unsigned
long long –263 (-9223372036854775808) to
263–1 (9223372036854775807) 64-bit signed

float Negative range: 32-bit IEEE 754


-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
long double Negative range: 80-bit
-1.18E+4932 to -3.37E-4932
Positive range:
3.37E-4932 to 1.18E+4932
Significant decimal digits: 19

28

28

14
1/29/20

sizeof Function
You can use the sizeof function to find the size of a type.
For example, the following statement displays the size of
int, long, and double on your machine.

cout << sizeof(int) << " " <<


sizeof(long) << " " << sizeof(double);
4 4 8

double area = 5.4;


cout << "Size of area: " << sizeof(area)
<< " bytes" << endl;
Size of area: 8 bytes
29

29

Numeric Literals

A literal is a constant value that appears directly in a


program. For example, 34, 1000000, and 5.0 are literals in
the following statements:

int i = 34;
long k = 1000000;
double d = 5.0;

30

30

15
1/29/20

octal and hex literals


• By default, an integer literal is a decimal number.
• To denote a binary integer literal, use a leading
0b or 0B (zero b).
• To denote an octal integer literal, use a leading 0
(zero)
• To denote a hexadecimal integer literal, use a
leading 0x or 0X (zero x).

cout << 10 << " " << 0b10 << " " << 010
<< " " << 0x10;
10 2 8 16
31

31

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 32

32

16
1/29/20

Numeric Operators

33

33

Integer Division
5 / 3 yields an integer 1.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

34

34

17
1/29/20

Remainder Operator
Remainder is very useful in programming. For example, an
even number % 2 is always 0 and an odd number % 2 is
always 1. So you can use this property to determine
whether a number is even or odd.
Suppose today is Saturday and you and your friends are
going to meet in 10 days. What day is in 10 days? You can
find that day is Tuesday using the following expression:
S M T W T F S
0 1 2 3 4 5 6

35

35

Example: Displaying Time


A program that obtains minutes from seconds.

DisplayTime Run

36

36

18
1/29/20

Exponent Operations
pow(a, b) = ab

cout << pow(2.0, 3) << endl;


8
cout << pow(4.0, 0.5) << endl;
2
cout << pow(2.5, 2) << endl;
6.25
cout << pow(2.5, -2) << endl;
0.16
37

37

Overflow
When a variable is assigned a value that is
too large to be stored, it causes overflow.
For example, executing the following
statement causes overflow, because the
largest value that can be stored in a variable
of the short type is 32767. 32768 is too
large.

short value = 32767 + 1;


38

38

19
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 39

39

Arithmetic Expressions

is translated to

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x +


(9+x)/y)

40

40

20
1/29/20

Precedence
() Operators contained within pairs of
parentheses are evaluated first.
* / % Multiplication, division, and remainder
operators are applied next.
+ - Addition and subtraction operators are
applied last.
→ If an expression contains several similar
operators, they are applied from left to right.

41

41

Precedence Example

42

42

21
1/29/20

Example: Converting
Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:

celsius = ( 95 )( fahrenheit - 32)

FahrenheitToCelsius Run

43

43

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 44

44

22
1/29/20

Displaying the Current Time


Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
The time(0) function in the ctime header file returns
the current time in seconds elapsed since the time
00:00:00 on January 1, 1970 GMT, as shown in Figure 2.1.
This time is known as the Unix epoch because 1970 was
the year when the Unix operating system was formally
introduced.
Elapsed
time
Time
Unix Epoch Current Time
01-01-1970 time(0)
00:00:00 GMT ShowCurrentTime Run
45

45

ShowCurrentTime.cpp
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// Obtain the total seconds since the midnight, Jan 1, 1970
int totalSeconds = time(0);
// Compute the current second in the minute in the hour
int currentSecond = totalSeconds % 60;
// Obtain the total minutes
int totalMinutes = totalSeconds / 60;
// Compute the current minute in the hour
int currentMinute = totalMinutes % 60;
// Obtain the total hours
long totalHours = totalMinutes / 60;
// Compute the current hour
int currentHour = (int)(totalHours % 24);
// Display results
cout << "Current time is " << currentHour << ":"
<< currentMinute << ":" << currentSecond << " GMT" << endl;
return 0;
46
}

46

23
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 47

47

Augmented Assignment Operators

48

48

24
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 49

49

Increment and Decrement Operators


Operator Name Description
++var pre- Increments var by 1 and evaluates to the new
increment value in var after the increment.
var++ post- Evaluates to the original value in var and
increment increments var by 1.
--var pre- Decrements var by 1 and evaluates to the new
decrement value in var after the decrement.
var-- post- Evaluates to the original value in var and
decrement decrements var by 1.

50

50

25
1/29/20

Increment and
Decrement Operators, cont.
What is the output of the following two sequences?

51

51

Increment and
Decrement Operators, cont.
Using increment and decrement operators makes
expressions short, but it also makes them complex
and difficult to read. Avoid using these operators in
expressions that modify multiple variables, or the
same variable for multiple times such as this:

int k = ++i + i; // Avoid!

52

52

26
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 53

53

Numeric Type Conversion


Consider the following statements:

short i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;

54

54

27
1/29/20

Type Casting
Implicit casting
double d = 3; // type widening

Explicit casting
int i = static_cast<int>(3.0);
// type narrowing
int i = (int)3.9; // C-style casting
// Fraction part is truncated

55

55

NOTE
Casting does not change the variable being cast.
For example, d is not changed after casting in
the following code:

double d = 4.5;
int i = static_cast<int>(d);
// d is not changed

56

56

28
1/29/20

NOTE

The GNU and Visual C++ compilers will give a


warning when you narrow a type unless you use
static_cast to make the conversion explicit.

57

57

Example: Keeping Two Digits


after Decimal Points
Write a program that displays the 6%-sales tax with
two digits after the decimal point.

cout << "Sales tax is " <<


static_cast<int>(tax * 100) / 100.0;

SalesTax Run

58

58

29
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 59

59

Case Study: Counting Monetary Units

This program lets the user enter the amount in decimal


representing dollars and cents and output a report
listing the monetary equivalent in single dollars,
quarters, dimes, nickels, and pennies.
Dollar = 100 cents
Quarters = 25 cents
Dime = 10 cents
Nickel = 5 cents ComputeChange Run

60

60

30
1/29/20

Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100; remainingAmount
initialized
// Find the number of quarters in the remaining
amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining


amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;

61

61

Trace ComputeChange
animation

Suppose amount is 11.56


int remainingAmount = (int)(amount * 100);
remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining


amount numberOfOneDollars
int numberOfQuarters = remainingAmount / 25; assigned
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining


amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;

62

62

31
1/29/20

Trace ComputeChange
animation

Suppose amount is 11.56


int remainingAmount = (int)(amount * 100);
remainingAmount 56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining


amount
int numberOfQuarters = remainingAmount / 25; remainingAmount
remainingAmount = remainingAmount % 25; updated

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining


amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;

63

63

Trace ComputeChange
animation

Suppose amount is 11.56


int remainingAmount = (int)(amount * 100);
remainingAmount 56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining


amount
int numberOfQuarters = remainingAmount / 25; numberOfOneQuarters 2
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10; numberOfOneQuarters
remainingAmount = remainingAmount % 10; assigned
// Find the number of nickels in the remaining
amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;

64

64

32
1/29/20

Trace ComputeChange
animation

Suppose amount is 11.56


int remainingAmount = (int)(amount * 100);
remainingAmount 6
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining


amount
int numberOfQuarters = remainingAmount / 25; numberOfQuarters 2
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10; remainingAmount
updated
// Find the number of nickels in the remaining
amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;

65

65

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 66

66

33
1/29/20

Common Errors
1. Undeclared or Uninitialized Variables
double interestRate = 0.05;
double interest = interestrate * 45;
2. Integer Overflow
short value = 32767 + 1; // is -32768
3. Round-off Errors
float a = 1000.43;
float b = 1000.0;
cout << a - b << endl;
displays 0.429993, not 0.43

67

67

Common Errors
4. Unintended Integer Division

(a) displays 1, (b) displays 1.5

5. Forgetting Header Files


#include <cmath> // needed for pow()
#include <ctime> // needed for time()

68

68

34
1/29/20

Outline
• Writing a Simple Program • Case Study: Displaying the
• Reading Input from the Current Time
Keyboard • Augmented Assignment
• Identifiers Operators
• Variables • Increment and Decrement
• Assignment Statements and Operators
Assignment Expressions • Numeric Type Conversions
• Named Constants • Case Study: Counting
• Numeric Data Types and Monetary Units
Operations • Common Errors
• Evaluating Expressions and
Operator Precedence 69

69

35
1/29/20

Chapter 3: Selections

Sections 3.1-3.16

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

1
1/29/20

Introduction

If you assigned a negative value for radius in


Listing 2.1, ComputeArea.cpp, the program would
print an invalid result. If the radius is negative, you
don't want the program to compute the area. How
can you deal with this situation?

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

2
1/29/20

The bool Type and Operators


Often in a program you need to compare two values,
such as whether i is greater than j. C++ provides six
relational operators (also known as comparison
operators):

The bool Type and Operators


A variable that holds a Boolean value is known as a
Boolean variable, which holds true or false.
bool lightsOn = true;
cout << lightsOn; // Displays 1
cout << (4 < 5); // Displays 1
cout << (4 > 5); // Displays 0

Any nonzero value evaluates to true and zero value


evaluates to false.
bool b1 = -1.5; // ≡ bool b1 = true;
bool b2 = 0; // ≡ bool b2 = false;
bool b3 = 1.5; // ≡ bool b3 = true;
6

3
1/29/20

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

One-way if Statements
if (booleanExpression)
{
statement(s);
}

if (radius >= 0)
{
area = radius * radius * PI;
cout << "The area for the circle of " <<
" radius " << radius << " is " << area;
} 8

4
1/29/20

Notes
• The boolean-expression must be enclosed in
parentheses.

• The braces can be omitted if they enclose a single


statement.

Simple if Demo
A program that prompts the user to enter an integer. If the number
is a multiple of 5, displays HiFive. If the number is even, displays
HiEven.

SimpleIfDemo Run

10

10

5
1/29/20

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

11

11

Two-Way if-else Statement


if (booleanExpression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}

12

12

6
1/29/20

Examples

13

13

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

14

14

7
1/29/20

Nested if Statements
You can nest multiple if statements

if (i > k)
{
if (j > k)
cout << "i and j are greater than k";
}
else
cout << "i is less than or equal to k";

15

15

Multiple Alternative if Statements

16

16

8
1/29/20

animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

17

17

animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

18

18

9
1/29/20

animation
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

19

19

animation
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

20

20

10
1/29/20

animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

21

21

Note
The else clause matches the most recent if clause in
the same block.

22

22

11
1/29/20

Note, cont.
Nothing is printed from the Statement (a) above. To force
the else clause to match the first if clause, you must
add a pair of braces:

int i = 1, j = 2, k = 3;
if (i > j)
{
if (i > k)
cout << "A";
}
else
cout << "B";

This statement prints B. 23

23

TIP

24

24

12
1/29/20

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

25

25

Common Errors
1: Forgetting Necessary Braces

26

26

13
1/29/20

Common Errors
2: Wrong Semicolon at the if Line

27

27

Common Errors
3: Mistakenly Using = for ==

if (count = 1)
cout << "count is zero" << endl;
else
cout << "count is not zero" << endl;

28

28

14
1/29/20

Common Errors
4: Redundant Testing of Boolean Values

29

29

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

30

30

15
1/29/20

Case Study: Body Mass Index


The Body Mass Index (BMI) is a measure of health on
weight. It can be calculated by taking your weight in
kilograms and dividing by the square of your height in
meters (𝐵𝑀𝐼 = &⁄'( ). The interpretation of BMI for
people 16 years or older is as follows:

ComputeBMI Run
31

31

Case Study: Body Mass Index

32

32

16
1/29/20

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

33

33

Case Study: Computing Taxes


The US federal personal income tax is calculated based on
the filing status and taxable income. There are four filing
statuses: single filers, married filing jointly, married filing
separately, and head of household. The tax rates for 2002
are shown below.

34

34

17
1/29/20

Computing Taxes: Skeleton Code


if (status == 0)
{
// Compute tax for single filers
}
else if (status == 1)
{
// Compute tax for married file jointly
}
else if (status == 2)
{
// Compute tax for married file separately
}
else if (status == 3)
{
// Compute tax for head of household
}
else
{ ComputeTax Run
// Display wrong status
}
35

35

Computing Taxes: First Case Details


if (status == 0)
{
// Compute tax for single filers
if (income <= 6000)
tax = income * 0.10;
else if (income <= 27950)
tax = 6000 * 0.10 + (income - 6000) * 0.15;
else if (income <= 67700)
tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +
(income - 27950) * 0.27;
else if (income <= 141250)

}
else if (status == 1)

36

36

18
1/29/20

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

37

37

Generating Random Numbers


• You can use the rand() function to obtain a
random integer.
• This function returns a random integer between 0
and RAND_MAX (32,767 in Visual C++).
• To start with a different seed at each execution,
use
srand(time(0));
• To obtain a random integer between 0 and 9, use
rand() % 10

38

38

19
1/29/20

Example: A Simple Math Learning Tool


• This example creates a program for a first grader to
practice subtractions.
• The program randomly generates two single-digit
integers number1 and number2 with number1
>= number2 and displays a question such as
“What is 9 – 2?” to the student.
• After the student types the answer, the program
displays a message to indicate whether the answer is
correct.

SubtractionQuiz Run

39

39

SubtractQuiz.cpp 1/2
#include <iostream>
#include <ctime> // for time function
#include <cstdlib> // for rand and srand functions
using namespace std;

int main()
{
// 1. Generate two random single-digit integers
srand(time(0));
int number1 = rand() % 10;
int number2 = rand() % 10;

// 2. If number1 < number2, swap number1 with number2


if (number1 < number2)
{
int temp = number1;
number1 = number2;
number2 = temp;
}
40

40

20
1/29/20

SubtractQuiz.cpp 2/2
// 3. Ask the student “what is number1 – number2?”
cout << "What is " << number1 << " - " << number2 << "? ";
int answer;
cin >> answer;

// 4. Grade the answer and display the result


if (number1 - number2 == answer)
cout << "You are correct!";
else
cout << "Your answer is wrong.\n“
<< number1 << " - “ << number2
<< " should be " << (number1 - number2) << endl;

return 0;
}

41

41

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

42

42

21
1/29/20

Logical Operators
• The logical operators !, &&, and || can be used to
create a compound Boolean expression.

43

43

44

44

22
1/29/20

Examples

A program that checks whether a number is


divisible by 2 and 3, whether a number is divisible
by 2 or 3, and whether a number is divisible by 2
or 3 but not both:

TestBooleanOperators Run

45

45

TestBooleanOperators.cpp
#include <iostream>
using namespace std;

int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;

if (number % 2 == 0 && number % 3 == 0)


cout << number << " is divisible by 2 and 3." << endl;
if (number % 2 == 0 || number % 3 == 0)
cout << number << " is divisible by 2 or 3." << endl;
if ((number % 2 == 0 || number % 3 == 0) &&
!(number % 2 == 0 && number % 3 == 0))
cout << number << " divisible by 2 or 3, but not both." << endl;

return(0);
}
46

46

23
1/29/20

Short-Circuit Operator
• When evaluating p1 && p2, C++ first evaluates p1
and then evaluates p2 if p1 is true; if p1 is false,
it does not evaluate p2.
• When evaluating p1 || p2, C++ first evaluates p1
and then evaluates p2 if p1 is false; if p1 is true,
it does not evaluate p2.
• Therefore, && is referred to as the conditional or
short-circuit AND operator, and || is referred to as the
conditional or short-circuit OR operator.

47

47

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

48

48

24
1/29/20

Case Study: Determining Leap Year


A program that lets the user enter a year and checks
whether it is a leap year.

A year is a leap year if it is divisible by 4 but not by 100 or


if it is divisible by 400. So you can use the following
Boolean expression to check whether a year is a leap
year:

(year % 4 == 0 && year % 100 != 0) ||


(year % 400 == 0)
LeapYear Run

49

49

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

50

50

25
1/29/20

Case Study: Lottery


Randomly generates a lottery of a two-digit number,
prompts the user to enter a two-digit number, and
determines whether the user wins according to the
following rule:

• If the user input matches the lottery in exact order,


the award is $10,000.
• If the user input matches the lottery, the award is
$3,000.
• If one digit in the user input matches a digit in the
lottery, the award is $1,000.
Lottery Run

51

Lottery.cpp 1/2
#include <iostream>
#include <ctime> // for time function
#include <cstdlib> // for rand and srand functions
using namespace std;

int main()
{
// Generate a lottery
srand(time(0));
int lottery = rand() % 100;

// Prompt the user to enter a guess


cout << "Enter your lottery pick (two digits): ";
int guess;
cin >> guess;

52

52

26
1/29/20

Lottery.cpp 1/2
// Check the guess
if (guess == lottery)
cout << "Exact match: you win $10,000" << endl;
else if (guess % 10 == lottery / 10
&& guess / 10 == lottery % 10)
cout << "Match all digits: you win $3,000" << endl;
else if (guess % 10 == lottery / 10
|| guess % 10 == lottery % 10
|| guess / 10 == lottery / 10
|| guess / 10 == lottery % 10)
cout << "Match one digit: you win $1,000" << endl;
else
cout << "Sorry, no match" << endl;

return 0;
}
53

53

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

54

54

27
1/29/20

switch Statements
switch (status)
{
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: cout << "Errors: invalid status" << endl;
}

55

55

switch Statement Flow Chart

56

56

28
1/29/20

switch Statement Rules


The switch-expression
must yield a integral value
and must always be
enclosed in parentheses.

The case values must be


integral constant expressions,
meaning that they cannot
contain variables in the
expression, such as 1 + x.

57

57

switch Statement Rules


The break is optional, but it
should be used at the end of
each case in order to
terminate the remainder of
the switch statement.

The default
case, which is optional,
can be used to perform When the value in a case statement matches the
actions when none of value of the switch-expression, the statements
the specified cases is starting from this case are executed until either
executed. a break statement or the end of the switch
statement is reached.
58

58

29
1/29/20

animation

Trace switch statement


Suppose day is 3:

59

59

animation

Trace switch statement


Execute case 3

60

60

30
1/29/20

animation

Trace switch statement


Fall to case 4

61

61

animation

Trace switch statement


Fall to case 5 then break

62

62

31
1/29/20

animation

Trace switch statement


Execute what is next

63

63

Example: Chinese Zodiac


A program that prompts the user to enter a year and
displays the animal for the year.

ChineseZodiac Run

64

64

32
1/29/20

ChineseZodiac.cpp

65

65

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

66

66

33
1/29/20

Conditional Expressions
A conditional expression evaluates an expression based
on a condition.

Syntax:
(booleanExpression) ? expression1 : expression2

The result of this conditional expression is expression1 if


boolean-expression is true; otherwise, the result is
expression2.

67

67

Examples
• Equivalent statements:

• Finding the max:

• Odd of even:

68

68

34
1/29/20

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

69

69

Operator Precedence and


Associativity
Operator precedence and associativity determine the
order in which operators are evaluated.

How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?


false?

3 + 4 * 4 > 5 * (4 + 3) – 1 && (4 – 3 > 5)?


false?

70

70

35
1/29/20

Operator Precedence

71

71

Operator Associativity

• All binary operators except assignment


operators are left associative.
• Assignment operators are right associative.

72

72

36
1/29/20

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

73

73

Debugging
• Debugging is the process of finding and fixing
errors in a program.
• Visual Studio supports debugging:
– Executing a single statement at a time
– Tracing into or stepping over a function
– Setting breakpoints
– Displaying variables
– Displaying call stacks
– Modifying variables
• Show demo on Visual Studio 2019.
74

74

37
1/29/20

Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging

75

75

38
1/29/20

Chapter 4: Mathematical
Functions, Characters, and Strings

Sections 4.1-4.11

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

1
1/29/20

Introduction
Suppose you need to estimate the area enclosed by four
cities, given the GPS locations (latitude and longitude) of
these cities, as shown in the following diagram. How
would you write a program to solve this problem? You will
be able to write such a program after completing this
chapter.

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

2
1/29/20

Mathematical Functions
C++ provides many useful functions in the cmath
header for performing common mathematical
functions.

1. Trigonometric functions
2. Exponent functions
3. Service functions

To use them, you need to include:


#include <cmath>

Trigonometric Functions

3
1/29/20

Exponent Functions

Service Functions
Function Description Example
ceil(x) x is rounded up to its nearest ceil(2.1) returns 3.0
integer. This integer is ceil(-2.1) returns -2.0
returned as a double value.
floor(x) x is rounded down to its floor(2.1) returns 2.0
nearest integer. This integer floor(-2.1) returns -3.0
is returned as a double value.
min(x, y) Returns the minimum of x max(2, 3) returns 3
and y.
max(x, y) Returns the maximum of x min(2.5, 4.6) returns
and y. 2.5
abs(x) Returns the absolute value of abs(-2.1) returns 2.1
x.
8

4
1/29/20

Case Study: Computing Angles


of a Triangle

A program that prompts the user to enter the x-


and y-coordinates of the three corner points in a
triangle and then displays the triangle’s angles.

ComputeAngles Run

ComputeAngles.cpp 1/2
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
// Prompt the user to enter three points
cout << "Enter three points: ";
double x1, y1, x2, y2, x3, y3;
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;

// Compute three sides


double a = sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3));
double b = sqrt((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3));
double c = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
10

10

5
1/29/20

ComputeAngles.cpp 2/2
// Obtain three angles in radians
double A = acos((a * a - b * b - c * c) / (-2 * b * c));
double B = acos((b * b - a * a - c * c) / (-2 * a * c));
double C = acos((c * c - b * b - a * a) / (-2 * a * b));

// Display the angles in degress


const double PI = 3.14159;
cout << "The three angles are " << A * 180 / PI << " "
<< B * 180 / PI << " " << C * 180 / PI << endl;

return 0;
}

11

11

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

12

12

6
1/29/20

Character Data Type


• A character data type represents a single character.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
• The increment and decrement operators can also be
used on char variables to get the next or preceding
character. For example, the following statements
display character b.
char ch = 'a';
cout << ++ch;
• The characters are encoded into numbers using the
ASCII code.
13

13

Appendix B: ASCII Character Set


ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

14

14

7
1/29/20

ASCII Character Set in the Hexadecimal Index

15

15

Read Characters
To read a character from the keyboard, use

cout << "Enter a character: ";


char ch;
cin >> ch; // Read a character

16

16

8
1/29/20

Escape Sequences
C++ uses a special notation to represent special character.

cout << "He said \"Hi\".\n";


The output is: He said "Hi". 17

17

Casting between char and


Numeric Types
• A char can be cast into any numeric type, and vice
versa.
• When an integer is cast into a char, only its lower 8 bits
of data are used; the other part is ignored.

int i = 'a';
// Same as int i = static_cast<int>('a');

char c = 97;
// Same as char c = static_cast<char>(97); 18

18

9
1/29/20

Numeric Operators on Characters


The char type is treated as if it is an integer of the byte
size. All numeric operators can be applied to char
operands.

Display

19

19

Example: Converting a Lowercase to


Uppercase
A program that prompts the user to enter a
lowercase letter and finds its corresponding
uppercase letter.

ToUppercase Run

20

20

10
1/29/20

Comparing and Testing Characters


• The ASCII for lowercase letters are consecutive integers
starting from the code for 'a', then for 'b', 'c', ..., and 'z'. The
same is true for the uppercase letters.
• The lower case of a letter is larger than its upper case by 32.
• Two characters can be compared using the comparison
operators just like comparing two numbers.
• 'a' < 'b' is true because the ASCII code for 'a' (97) is
less than the ASCII code for 'b' (98).
• 'a' < 'A' is false.
• '1' < '8' is true.

21

21

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

22

22

11
1/29/20

Case Study: Generating Random


Characters
The rand() function returns a random integer. You can
use it to write a simple expression to generate random
numbers in any range.

23

23

Case Study: Generating Random


Characters, cont.
Every character has a unique ASCII code between 0 and 127. To
generate a random character is to generate a random integer
between 0 and 127. The srand(seed) function is used to set a
seed.

DisplayRandomCharacter Run
24

24

12
1/29/20

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

25

25

Case Study: Guessing Birthdays


• The program can find your birth date. The program
prompts you to answer whether your birth date is in
the following five sets of numbers:

GuessBirthday Run

26

26

13
1/29/20

Case Study: Guessing Birthdays

27

27

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

28

28

14
1/29/20

Character Functions
C++ contains functions for working with characters.

CharacterFunctions Run

29

29

Example using Character


Functions

CharacterFunctions Run

30

30

15
1/29/20

Character Functions

• You can use isupper(), islower() and


isdigit() in the code below.

31

31

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

32

32

16
1/29/20

Case Study: Converting a Hexadecimal


Digit to a Decimal Value
A program that converts a hexadecimal digit to decimal.

HexDigit2Dec Run

33

33

HexDigit2Dec.cpp

34

34

17
1/29/20

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

35

35

The string Type


A string is a sequence of characters.
#include <string>
string s;
string message = "Programming is fun";

36

36

18
1/29/20

String Subscript Operator


C++ provides the subscript operator for accessing the
character at a specified index in a string using the
syntax stringName[index].
string s = "welcome to C++";
s.at(0) = 'W';
cout << s.length() << s[0] << endl;
14W

37

37

Concatenating Strings
C++ provides the + operator for concatenating two strings.

string s3 = s1 + s2;

string m = "Good";
m += " morning";
m += '!';
cout << m << endl;
Good morning!
38

38

19
1/29/20

Comparing Strings
You can use the relational operators ==, !=, <, <=, >, >= to
compare two strings. This is done by comparing their
corresponding characters on by one from left to right.
For example,

39

39

Reading Strings
Reading a word:

Reading a line using getline(cin, s, delimitCharacter):

40

40

20
1/29/20

Example: Order Two Cities


A program that prompts the user to enter two
cities and displays them in alphabetical order.

OrderTwoCities Run

41

41

OrderTwoCities.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
string city1, city2;
cout << "Enter the first city: ";
getline(cin, city1);
cout << "Enter the second city: ";
getline(cin, city2);

cout << "The cities in alphabetical order are ";


if (city1 < city2)
cout << city1 << " " << city2 << endl;
else
cout << city2 << " " << city1 << endl;

return 0;
} 42

42

21
1/29/20

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

43

43

Case Study: Revising the Lottery


Program Using Strings
A problem can be solved using many different approaches.
This section rewrites the lottery program in Listing 3.7 using
strings. Using strings simplifies this program.

LotteryUsingStrings Run 44

44

22
1/29/20

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

45

45

Formatting Console Output


You can use the stream manipulators to display formatted
output on the console.

46

46

23
1/29/20

setprecision(n) Manipulator
#include <iomanip>

displays
12.3 12.35 12.346 12.3457

47

47

fixed Manipulator
cout << 232123434.357;
displays
2.32123e+08

cout << fixed << 232123434.357;


displays
232123434.357000

cout << fixed << setprecision(2)


<< 232123434.357;
displays
232123434.36
48

48

24
1/29/20

showpoint Manipulator
cout << setprecision(6);
cout << 1.23 << endl;
cout << showpoint << 1.23 << endl;
cout << showpoint << 123.0 << endl;
displays
1.23
1.23000
123.000

49

49

setw(width) Manipulator

displays
C++ 101
Java 101
HTML 101

Prgramming#101
50

50

25
1/29/20

left and right Manipulators

displays
□□□□1.23
□□351.34

51

51

left and right Manipulators

displays
1.23□□□□351.34□□

52

52

26
1/29/20

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

53

53

Simple File Output


To write data to a file, first declare a variable of the ofstream
type:
#include <fstream>
ofstream output;
To specify a file, invoke the open function from output object as
follows:
output.open("numbers.txt");
Optionally, you can create a file output object and open the file in
one statement like this:
ofstream output("numbers.txt");

To write data, use the stream insertion operator (<<) in the same
way that you send data to the cout object. For example,
output << 95 << " " << 56 << " " << 34 << endl;
Finally:
output.close(); SimpleFileOutput Run

54

54

27
1/29/20

Simple File Input


To read data from a file, first declare a variable of the ifstream
type:
#include <fstream>
ifstream input;
To specify a file, invoke the open function from input as follows:
input.open("numbers.txt");
Or:
ifstream input("numbers.txt");
To read data, use the stream extraction operator (>>) in the same
way that you read data from the cin object. For example,
input >> score1 >> score2 >> score3;
Finally: Run
SimpleFileInput
input.close();
55

55

Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

56

56

28
1/29/20

Chapter 5: Loops

Sections 5.1-5.6, 5.9

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline
• Introduction
• The while Loop
• The do-while Loop
• The for Loop
• Which Loop to Use?
• Nested Loops
• Keywords break and continue

1
1/29/20

Introduction
Suppose that you need to print a string (e.g.,
"Welcome to C++!") a hundred times. It would be
tedious to have to write the following statement a
hundred times:

cout << "Welcome to C++!" << endl;

Introduction
cout << "Welcome to Java!" << endl;
cout << "Welcome to Java!" << endl;
cout << "Welcome to Java!" << endl;
cout << "Welcome to Java!" << endl;
cout << "Welcome to Java!" << endl;

100
times …

cout << "Welcome to Java!" << endl;


cout << "Welcome to Java!" << endl;
cout << "Welcome to Java!" << endl;
cout << "Welcome to Java!" << endl;
cout << "Welcome to Java!" << endl;

So, how do you solve this problem?


4

2
1/29/20

Outline
• Introduction
• The while Loop
• The do-while Loop
• The for Loop
• Which Loop to Use?
• Nested Loops
• Keywords break and continue

Introducing while Loops


A while loop executes statements repeatedly while the
condition is true.

int count = 0;
while (count < 100)
{
cout << "Welcome to C++!\n";
count++;
}

3
1/29/20

while Loop Flow Chart

animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}

4
1/29/20

animation

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}

animation

Trace while Loop, cont.


Print Welcome to C++
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}

10

10

5
1/29/20

animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 1 now

while (count < 2)


{
cout << "Welcome to C++!";
count++;
}

11

11

animation

Trace while Loop, cont.


(count < 2) is still true since count
int count = 0; is 1

while (count < 2)


{
cout << "Welcome to C++!";
count++;
}

12

12

6
1/29/20

animation

Trace while Loop, cont.


Print Welcome to C++
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}

13

13

animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 2 now

while (count < 2)


{
cout << "Welcome to C++!";
count++;
}

14

14

7
1/29/20

animation

Trace while Loop, cont.


(count < 2) is false since count is 2
int count = 0; now

while (count < 2)


{
cout << "Welcome to C++!";
count++;
}

15

15

animation

Trace while Loop


The loop exits. Execute the next
int count = 0; statement after the loop.

while (count < 2)


{
cout << "Welcome to C++!";
count++;
}

16

16

8
1/29/20

Case Study: Guessing Numbers


Write a program that randomly generates an
integer between 0 and 100, inclusive. The
program prompts the user to enter a number
continuously until the number matches the
randomly generated number. For each user input,
the program tells the user whether the input is
too low or too high, so the user can choose the
next input intelligently. Here is a sample run:
GuessNumberOneTime Run

GuessNumber Run

17

17

GuessNumber.cpp 1/2
#include <iostream>
#include <cstdlib>
#include <ctime> // Needed for the time function
using namespace std;

int main()
{
// Generate a random number to be guessed
srand(time(0));
int number = rand() % 101;

cout << "Guess a magic number between 0 and 100";

18

18

9
1/29/20

GuessNumber.cpp 1/2
int guess = -1;
while (guess != number)
{
// Prompt the user to guess the number
cout << "\nEnter your guess: ";
cin >> guess;

if (guess == number)
cout << "Yes, the number is " << number << endl;
else if (guess > number)
cout << "Your guess is too high" << endl;
else
cout << "Your guess is too low" << endl;
} // End of loop

return 0;
19
}

19

Loop Design Strategy

20

20

10
1/29/20

Case Study: Multiple Subtraction Quiz


Take the subtraction quiz 5 times.

Report number of correct answers and the quiz


time.

SubtractionQuiz Run

21

21

SubtractionQuizLoop.cpp 1/3
#include <iostream>
#include <ctime> // Needed for time function
#include <cstdlib> // Needed for the srand and rand functions
using namespace std;
int main()
{
int correctCount = 0; // Count the number of correct answers
int count = 0; // Count the number of questions
long startTime = time(0);
const int NUMBER_OF_QUESTIONS = 5;
srand(time(0)); // Set a random seed
while (count < NUMBER_OF_QUESTIONS)
{ See next slides }
long endTime = time(0);
long testTime = endTime - startTime;
cout << "Correct count is " << correctCount << "\nTest time is "
<< testTime << " seconds\n";
return 0;
}
22

22

11
1/29/20

SubtractionQuizLoop.cpp 2/3
while (count < NUMBER_OF_QUESTIONS)
{
// 1. Generate two random single-digit integers
int number1 = rand() % 10;
int number2 = rand() % 10;

// 2. If number1 < number2, swap number1 with number2


if (number1 < number2)
{
int temp = number1;
number1 = number2;
number2 = temp;
}

23

23

SubtractionQuizLoop.cpp 3/3
// 3. Prompt the student to answer “what is num1 – num2?”
cout << "What is " << number1 << " - " << number2 << "? ";
int answer;
cin >> answer;
// 4. Grade the answer and display the result
if (number1 - number2 == answer)
{
cout << "You are correct!\n";
correctCount++;
}
else
cout << "Your answer is wrong.\n" << number1 << " - " <<
number2 << " should be " << (number1 - number2) << endl;
// Increase the count
count++;
} 24

24

12
1/29/20

Controlling a Loop with User


Confirmation

25

25

Controlling a Loop with a Sentinel Value


You may use an input value to signify the end of the loop.
Such a value is known as a sentinel value.

A program that reads and calculates the sum of an


unspecified number of integers. The input 0 signifies the
end of the input.

SentinelValue Run

26

26

13
1/29/20

SentinelValue.cpp
int data;
cin >> data;

// Keep reading data until the input is 0


int sum = 0;
while (data != 0)
{
sum += data;

// Read the next data


cout << "Enter an integer (the input ends " <<
"if it is 0): ";
cin >> data;
}

cout << "The sum is " << sum << endl;


27

27

Input and Output Redirections


• If you have a large number of data to enter, it would be
cumbersome to type from the keyboard.
• You may store the data separated by whitespaces in a
text file, say input.txt, and run the program and
redirecting input to the file.
• You can also redirect program output to a text file, say
outpu.txt.

SentinelValue.exe < input.txt > output.txt

28

28

14
1/29/20

Reading Data from a File


• If you have many numbers to read from a file,
you need to write a loop to read all these
numbers.
• You can invoke the eof() function on the input
object to detect the end of file.
• A program that reads all numbers from the file
numbers.txt.

ReadAllData Run

29

29

ReadAllData.cpp
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Open a file
ifstream input("numbers.txt");

double sum = 0;
double number;
while (!input.eof()) // Read data to the end of file
{
input >> number; // Read data
cout << number << " "; // Display data
sum += number;
}
input.close();
cout << "\nTotal is " << sum << endl;
return 0;
} 30

30

15
1/29/20

Caution

• Don’t use floating-point values for equality checking in a


loop control expression; they are approximations, using
them can result in inaccurate results.
• The following loop does not stop.

double item = 1;
double sum = 0;
while (item != 0) // No guarantee it will be 0
{
sum += item;
item -= 0.1;
}
31

31

Outline
• Introduction
• The while Loop
• The do-while Loop
• The for Loop
• Which Loop to Use?
• Nested Loops
• Keywords break and continue

32

32

16
1/29/20

do-while Loop
A do-while loop is the same as
a while loop except that it
executes the loop body first and
then checks the loop
continuation condition.

TestDoWhile Run
33

33

TestDoWhile.cpp
// Initialize data and sum
int data = 0;
int sum = 0;

do
{
sum += data;

// Read the next data


cout << "Enter an integer (the input ends " <<
"if it is 0): ";
cin >> data; // Keep reading until the input is 0
} while (data != 0);

cout << "The sum is " << sum << endl;

34

34

17
1/29/20

Outline
• Introduction
• The while Loop
• The do-while Loop
• The for Loop
• Which Loop to Use?
• Nested Loops
• Keywords break and continue

35

35

for Loops

A for loop has a


concise syntax for
writing loops.

36

18
1/29/20

animation

Trace for Loop


Declare i

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

37

37

animation

Trace for Loop, cont.


Execute initializer
i is now 0

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

38

38

19
1/29/20

animation

Trace for Loop, cont.


(i < 2) is true
since i is 0

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

39

39

animation

Trace for Loop, cont.


Print Welcome to C++!

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

40

40

20
1/29/20

animation

Trace for Loop, cont.


Execute adjustment statement
i now is 1

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

41

41

animation

Trace for Loop, cont.


(i < 2) is still true
since i is 1

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

42

42

21
1/29/20

animation

Trace for Loop, cont.


Print Welcome to C++

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

43

43

animation

Trace for Loop, cont.


Execute adjustment statement
i now is 2

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

44

44

22
1/29/20

animation

Trace for Loop, cont.


(i < 2) is false
since i is 2

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

45

45

animation

Trace for Loop, cont.


Exit the loop. Execute the next
statement after the loop

int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}

46

46

23
1/29/20

Note
• The initial-action in a for loop can be a list of zero
or more comma-separated expressions.

• The action-after-each-iteration in a for loop


can be a list of zero or more comma-separated
statements.

47

47

Note
• If the loop-continuation-condition in a for loop
is omitted, it is implicitly true. Thus the for statement
given below, which is an infinite loop, is correct.
• It is better to use the equivalent while loop to avoid
confusion:

48

48

24
1/29/20

Outline
• Introduction
• The while Loop
• The do-while Loop
• The for Loop
• Which Loop to Use?
• Nested Loops
• Keywords break and continue

49

49

Which Loop to Use?


• The loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of
these three forms.
• The while loop can always be converted into the for loop.

• The for loop can generally be converted into the while loop.

50

50

25
1/29/20

Which Loop to Use?


• Use the one that is most intuitive and comfortable for
you.
• In general, a for loop may be used if the number of
repetitions is counter-controlled, as, for example,
when you need to print a message 100 times.
• A while loop may be used if the number of
repetitions is sentinel-controlled, as in the case of
reading the numbers until the input is 0.
• A do-while loop can be used to replace a while loop
if the loop body has to be executed before testing the
continuation condition.
51

51

Outline
• Introduction
• The while Loop
• The do-while Loop
• The for Loop
• Which Loop to Use?
• Nested Loops
• Keywords break and continue

52

52

26
1/29/20

Nested Loops
A loop can be nested inside another loop.

Example: A program that uses nested for loops to print a


multiplication table.

MultiplicationTable Run

53

53

MultiplicationTable.cpp 1/2
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
cout << " Multiplication Table\n";

// Display the number title


cout << " | ";
for (int j = 1; j <= 9; j++)
cout << setw(3) << j;
cout << "\n";

cout << "--------------------------------\n";


54

54

27
1/29/20

MultiplicationTable.cpp 2/2
// Display table body
for (int i = 1; i <= 9; i++)
{
cout << i << " | ";
for (int j = 1; j <= 9; j++)
{
// Display the product and align properly
cout << setw(3) << i * j;
}
cout << "\n";
}

return 0;
}

55

55

Outline
• Introduction
• The while Loop
• The do-while Loop
• The for Loop
• Which Loop to Use?
• Nested Loops
• Keywords break and continue

56

56

28
1/29/20

Using break and continue


Use break in a loop to immediately terminate the
loop.
Example: adding integers from 1 to 20 until sum is
greater than or equal to 100.
while (number < 20)
{
number++;
sum += number;
if (sum >= 100)
break; TestBreak Run

}
57

57

Using break and continue


Use continue in a loop to proceed to the next
iteration.
Example: adding integers from 1 to 20 except 10 and 11.

while (number < 20)


{
number++;
if (number == 10 || number == 11)
continue;
sum += number;
} TestContinue Run
58

58

29
1/29/20

Outline
• Introduction
• The while Loop
• The do-while Loop
• The for Loop
• Which Loop to Use?
• Nested Loops
• Keywords break and continue

59

59

30
1/29/20

Chapter 6: Functions

Sections 6.1-6.13

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
2

1
1/29/20

Introduction

Find the sum of integers from 1 to 10, from 20 to 37,


and from 35 to 49, respectively.

Introduction
int sum = 0; Write 3 loops
for (int i = 1; i <= 10; i++)
sum += i;
cout << "Sum from 1 to 10 is " << sum << endl;

sum = 0;
for (int i = 20; i <= 37; i++)
sum += i;
cout << "Sum from 20 to 37 is " << sum << endl;

sum = 0;
for (int i = 35; i <= 49; i++)
sum += i;
cout << "Sum from 35 to 49 is " << sum << endl;
4

2
1/29/20

Introduction
int sum = 0; Very similar 3
for (int i = 1; i <= 10; i++) loops
sum += i;
cout << "Sum from 1 to 10 is " << sum << endl;

sum = 0;
for (int i = 20; i <= 37; i++)
sum += i;
cout << "Sum from 20 to 37 is " << sum << endl;

sum = 0;
for (int i = 35; i <= 49; i++)
sum += i;
cout << "Sum from 35 to 49 is " << sum << endl;
5

Introduction
Functions can be used to define reusable code and
organize and simplify code.
int sum(int i1, int i2)
{
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}

int main()
{
cout << "Sum from 1 to 10 is " << sum(1, 10) << endl;
cout << "Sum from 20 to 37 is " << sum(20, 37) << endl;
cout << "Sum from 35 to 49 is " << sum(35, 49) << endl;
return 0;
} 6

3
1/29/20

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
7

Defining a Function
• A function is a collection of statements that are
grouped together to perform an operation.
• A function definition consists of its function name,
parameters, return value type, and body.

4
1/29/20

Defining Functions, cont.


• Function signature is the combination of the
function name and the parameter list.
• The variables defined in the function header
are known as formal parameters.
• When a function is invoked, you pass a value to
the parameter. This value is referred to as
actual parameter or argument.

Defining Functions, cont.


• A Function may return a value.
• The return value type is the data type of the
value the function returns.
• If the function does not return a value, the
return value type is the keyword void.

10

10

5
1/29/20

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
11

11

Calling a Function
This program demonstrates calling a Function
max to return the largest of the int values

TestMax Run

12

12

6
1/29/20

animation

Trace Function Invocation


i is now 5

13

13

animation

Trace Function Invocation


j is now 2

14

14

7
1/29/20

animation

Trace Function Invocation


invoke max(i, j)

15

15

animation

Trace Function Invocation


invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

16

16

8
1/29/20

animation

Trace Function Invocation


declare variable result

17

17

animation

Trace Function Invocation


(num1 > num2) is true since num1
is 5 and num2 is 2

18

18

9
1/29/20

animation

Trace Function Invocation


result is now 5

19

19

animation

Trace Function Invocation


return result, which is 5

20

20

10
1/29/20

animation

Trace Function Invocation


return max(i, j) and assign the
return value to k

21

21

animation

Trace Function Invocation


Execute the print statement

22

22

11
1/29/20

Call Stacks
• Each time a function is invoked, the system
creates an activation record.
• The activation record is placed in an area of
memory known as a call stack.

23

23

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
24

24

12
1/29/20

void Functions
A void function does not return a value.

Want to print the grade for a given score.


Two solutions:
1. printGrade prints the grade
2. getGrade prints the grade

TestVoidFunction Run

TestReturnGradeFunction Run

25

25

void Functions
void printGrade(double score) char getGrade(double score)
{ {
if (score >= 90.0) if (score >= 90.0)
cout << 'A' << endl; return 'A';
else if (score >= 80.0) else if (score >= 80.0)
cout << 'B' << endl; return 'B';
else if (score >= 70.0) else if (score >= 70.0)
cout << 'C' << endl; return 'C';
else if (score >= 60.0) else if (score >= 60.0)
cout << 'D' << endl; return 'D';
else else
cout << 'F' << endl; return 'F';
} }

int main() int main()


{ {
cout << "Enter a score: "; cout << "Enter a score: ";
double score; double score;
cin >> score; cin >> score;

cout << "The grade is "; cout << "The grade is ";
printGrade(score); cout << getGrade(score) << endl;
return 0; return 0; 26
} }

26

13
1/29/20

Terminating a Program
• You can terminate a void printGrade(double score)
{
program at abnormal if (score < 0 || score > 100)

conditions by calling {
cout << "Invalid score" << endl;
exit(n). exit(1);

• Select the integer n to }


if (score >= 90.0)
specify the error type. cout << 'A';
else if (score >= 80.0)
cout << 'B';
else if (score >= 70.0)
cout << 'C';
else if (score >= 60.0)
cout << 'D';
else
cout << 'F';
}
27

27

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
28

28

14
1/29/20

Passing Arguments by Value


• By default, the arguments
are passed by value to
parameters when
invoking a function. void nPrint(char ch, int n)
• When calling a function, {
you need to provide for (int i = 0; i < n; i++)
arguments, which must cout << ch;
be given in the same }
order as their respective
parameters in the nPrint('a', 3);
function signature.
• The shown code prints a aaa
character 3 times.

29

29

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
30

30

15
1/29/20

Modularizing Code
• Modularizing makes the code easy to maintain and
debug and enables the code to be reused.
• These two examples use functions to reduce
complexity.

GreatestCommonDivisorFunction Run

PrimeNumberFunction Run

31

31

GreatestCommonDivisorFunction.cpp
int gcd(int n1, int n2)
{
int gcd = 1; // Initial gcd is 1
int k = 2; // Possible gcd

while (k <= n1 && k <= n2)


{
if (n1 % k == 0 && n2 % k == 0)
gcd = k; // Update gcd
k++;
}
return gcd; // Return gcd
}
int main()
{
...
cout << "The greatest common divisor for " << n1 <<
" and " << n2 << " is " << gcd(n1, n2) << endl;

return 0;
}
32

32

16
1/29/20

PrimeNumberFunction.cpp 1/3
#include <iostream>
#include <iomanip>
using namespace std;

// Check whether number is prime


bool isPrime(int number)
{
for (int divisor = 2; divisor <= number / 2; divisor++)
{
if (number % divisor == 0)
{
// If true, number is not prime
return false; // number is not a prime
}
}

return true; // number is prime


}
33

33

PrimeNumberFunction.cpp 2/3
void printPrimeNumbers(int numberOfPrimes)
{
int count = 0; // Count the number of prime numbers
int number = 2; // A number to be tested for primeness

// Repeatedly find prime numbers


while (count < numberOfPrimes)
{
// Print the prime number and increase the count
if (isPrime(number))
{
count++; // Increase the count
if (count % 10 == 0) // 10 numbers per line
{
// Print the number and advance to the new line
cout << setw(4) << number << endl;
}
else
cout << setw(4) << number;
}
number++; // Check if the next number is prime
} 34
}

34

17
1/29/20

PrimeNumberFunction.cpp 3/3
int main()
{
cout << "The first 50 prime numbers are \n";
printPrimeNumbers(50);

return 0;
}

35

35

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
36

36

18
1/29/20

Overloading Functions
Overloading functions enables you to define
functions with the same name as long as their
signatures are different.
• The max function that was used earlier works only with
the int data type.
• We can define and use other max functions that
accept different parameter counts and types.

TestFunctionOverloading Run

37

37

TestFunctionOverloading.cpp 1/2
#include <iostream>
using namespace std;

// Return the max between two int values


int max(int num1, int num2)
{
if (num1 > num2)
return num1;
else
return num2;
}

// Find the max between two double values


double max(double num1, double num2)
{
if (num1 > num2)
return num1;
else
return num2;
} 38

38

19
1/29/20

TestFunctionOverloading.cpp 2/2
// Return the max among three double values
double max(double num1, double num2, double num3)
{
return max(max(num1, num2), num3);
}

int main()
{
// Invoke the max function with int parameters
cout << "The max between 3 and 4 is " << max(3, 4) << endl;

// Invoke the max function with the double parameters


cout << "The maximum between 3.0 and 5.4 is "
<< max(3.0, 5.4) << endl;

// Invoke the max function with three double parameters


cout << "The maximum between 3.0, 5.4, and 10.14 is "
<< max(3.0, 5.4, 10.14) << endl;

return 0;
} 39

39

Ambiguous Invocation
Sometimes there may be two or more possible
matches for an invocation of a function, but the
compiler cannot determine the most specific
match. This is referred to as ambiguous
invocation. Ambiguous invocation is a
compilation error.

40

40

20
1/29/20

Ambiguous Invocation
#include <iostream>
using namespace std;
int maxNumber(int num1, double num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
double maxNumber(double num1, int num2)
{
if (num1 > num2)
return num1; maxNumber(1.0, 2)
else And
return num2; maxNumber(1, 2.0)
} Are OK
int main()
{
cout << maxNumber(1, 2) << endl; // Compilation error
return 0;
} 41

41

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
42

42

21
1/29/20

Function Prototypes
• Before a function is called, it must be declared first.
• One way to ensure it is to place the declaration before all
function calls.
• Another way to approach it is to declare a function
prototype before the function is called.
• A function prototype is a function declaration without
implementation.
• The implementation can be given later in the program.

TestFunctionPrototype Run
43

43

TestFunctionPrototype.cpp
#include <iostream>
using namespace std;
// Function prototype
int max(int num1, int num2);
double max(double num1, double num2);
double max(double num1, double num2, double num3);

int main()
{
// Invoke the max function with int parameters
cout << "The maximum between 3 and 4 is " <<
max(3, 4) << endl;
...
}
// Return the max between two int values
int max(int num1, int num2)
{ Or simply:
if (num1 > num2) int max(int, int);
return num1; double max(double, double);
else double max(double, double, double);
return num2;
}
... 44

44

22
1/29/20

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
45

45

Default Arguments
You can define default values for parameters in a
function.
The default values are passed to the parameters
when a function is invoked without the arguments.

DefaultArgumentDemo Run

46

46

23
1/29/20

DefaultArgumentDemo.cpp
#include <iostream>
using namespace std;

// Display area of a circle


void printArea(double radius = 1)
{
double area = radius * radius * 3.14159;
cout << "area is " << area << endl;
}

int main()
{
printArea();
printArea(4);

return 0;
}
47

47

Default Arguments
• When a function contains a mixture of parameters
with and without default values, those with default
values must be declared last.

• When an argument is left out of a function, all


arguments that come after it must be left out as well.

48

48

24
1/29/20

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
49

49

Inline Functions
C++ provides inline functions for improving performance for
short functions.

• Inline functions are not called; rather, the compiler


copies the function code in line at the point of each
invocation.
• To specify an inline function, precede the function
declaration with the inline keyword.
• Inline functions are desirable for short functions but not
for long ones.
InlineDemo Run

InlineExpandedDemo
50

50

25
1/29/20

InlineDemo.cpp
#include <iostream>
using namespace std;

inline void f(int month, int year)


{
cout << "month is " << month << endl;
cout << "year is " << year << endl;
}

int main()
{
int month = 10, year = 2008;
f(month, year); // Invoke inline function
f(9, 2010); // Invoke inline function

return 0;
}
51

51

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
52

52

26
1/29/20

Scope of Variables
• Scope: the part of the program where the
variable can be referenced.
• The scope of a variable starts from its
declaration and continues to the end of the
block that contains the variable.
• A variable can be declared as a local, a global,
or a static local.
• A local variable: a variable defined inside a
function.
• You can declare a local variable with the same
name in different blocks.
53

53

Scope of Local Variables


• A variable declared in the initial action part of a for loop
has its scope in the entire loop.
• A variable declared inside a for loop body has its scope
limited the rest of the loop body.

54

54

27
1/29/20

Scope of Local Variables, cont.


• It is acceptable to declare a local variable with the same
name in different non-nesting blocks.
• Avoid using same variable name in nesting blocks to
minimize making mistakes.

55

55

Global Variables
• Global variables are declared outside all
functions and are accessible to all functions in
their scope.
• Local variables do not have default values, but
global variables are defaulted to zero.

VariableScopeDemo Run

56

56

28
1/29/20

VariableScopeDemo.cpp
#include <iostream>
using namespace std;
void t1()
void t1(); // Function prototype
{
void t2(); // Function prototype int x = 1;
cout << "x is " << x << endl;
int main() cout << "y is " << y << endl;
{ x++;
t1(); y++;
t2(); }

return 0; void t2()


{
}
int x = 1;
cout << "x is " << x << endl;
int y; // Global variable cout << "y is " << y << endl;
// default to 0 }

57

57

Unary Scope Resolution


If a local variable name is the same as a global variable
name, you can access the global variable using
::globalVariable. The :: operator is known as the
unary scope resolution.
#include <iostream>
using namespace std;
int v1 = 10;
int main()
{
int v1 = 5;
cout << "local variable v1 is " << v1 << endl;
cout << "global variable v1 is " << ::v1 << endl;
return 0;
local variable v1 is 5
}
global variable v1 is 10
58

58

29
1/29/20

Static Local Variables


• After a function completes its execution, all its local
variables are destroyed.
• To retain the value stored in local variables so that they
can be used in the next call, use static local variables.
• Static local variables are permanently allocated in the
memory for the lifetime of the program.
• To declare a static variable, use the keyword static.

StaticVariableDemo Run

59

59

StaticVariableDemo.cpp
#include <iostream>
using namespace std;

void t1(); // Function prototype

int main()
{
t1();
t1();
return 0;
}

void t1()
{
static int x = 1; // Static local
int y = 1; // Local, not static
x++;
y++;
cout << "x is " << x << endl;
cout << "y is " << y << endl;
} 60

60

30
1/29/20

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
61

61

Pass by Value
• When you invoke a function with a
parameter, the value of the argument is
passed to the parameter. This is referred to
as pass-by-value.
• The variable is not affected, regardless of the
changes made to the parameter inside the
function.

Increment Run

62

62

31
1/29/20

Increment.cpp
#include <iostream>
using namespace std;

void increment(int n)
{
n++;
cout << "\tn inside the function is " << n << endl;
}

int main()
{
int x = 1;
cout << "Before the call, x is " << x << endl;
increment(x);
cout << "after the call, x is " << x << endl;

return 0;
}

63

63

Reference Variables
• A reference variable can be used as a function parameter to
reference the original variable.
• A reference variable is an alias for another variable.
• Any changes made through the reference variable are
actually performed on the original variable.
• To declare a reference variable, place the ampersand (&) in
front of the name.

TestReferenceVariable Run

64

64

32
1/29/20

TestReferenceVariable.cpp
#include <iostream>
using namespace std;

int main()
{
int count = 1;
int& r = count;
cout << "count is " << count << endl;
cout << "r is " << r << endl;

r++;
cout << "count is " << count << endl;
cout << "r is " << r << endl;

count = 10;
cout << "count is " << count << endl;
cout << "r is " << r << endl;

return 0;
65
}

65

Pass By Reference
Parameters can be passed by reference, which makes
the formal parameter an alias of the actual argument.
Thus, changes made to the parameters inside the
function also made to the arguments.

SwapByReference Run

66

66

33
1/29/20

SwapByReference.cpp 1/2
#include <iostream>
using namespace std;

// Swap two variables


void swap(int& n1, int& n2)
{
cout << "\tInside the swap function" << endl;
cout << "\tBefore swapping n1 is " << n1 <<
" n2 is " << n2 << endl;

// Swap n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;

cout << "\tAfter swapping n1 is " << n1 <<


" n2 is " << n2 << endl;
} 67

67

SwapByReference.cpp 2/2
int main()
{
// Declare and initialize variables
int num1 = 1;
int num2 = 2;

cout << "Before invoking the swap function, num1 is "


<< num1 << " and num2 is " << num2 << endl;

// Invoke the swap function to attempt to swap two variables


swap(num1, num2);

cout << "After invoking the swap function, num1 is " << num1
<< " and num2 is " << num2 << endl;

return 0;
}
68

68

34
1/29/20

Pass-by-Value vs. Pass-by-


Reference
• In pass-by-value, the actual parameter and its formal
parameter are independent variables.
• In pass-by-reference, the actual parameter and its
formal parameter refer to the same variable.
• Pass-by-reference is more efficient than pass-by-value.
However, the difference is negligible for parameters of
primitive types such as int and double.
• So, if a primitive data type parameter is not changed
in the function, you should declare it as pass-by-value
parameter.

69

69

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
70

70

35
1/29/20

Constant Reference Parameters


You can specify a constant reference parameter to
prevent its value from being changed by accident.
// Return the max between two numbers
int max(const int& num1, const int& num2)
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

71

71

Outline
• Introduction
• Defining a Function
• Calling a Function
• void Functions
• Passing Arguments by Value
• Modularizing Code
• Overloading Functions
• Function Prototypes
• Default Arguments
• Inline Functions
• Local, Global, and Static Local Variables
• Passing Arguments by Reference
• Constant Reference Parameters
72

72

36
Chapter 7: Single-Dimensional
Arrays and C-Strings

Sections 7.1-7.7, 7.11

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
2

2
Introduction
• How to read one #include <iostream>
using namespace std;
hundred numbers and int main()
compute their average? {
double numbers[100];
• double sum = 0;

• Use A1, A2, …, A100? for (int i = 0; i < 100; i++)


{
cout << "Enter a number: ";
cin >> numbers[i];
• Or use a single array }
sum += numbers[i];

that stores all the double average = sum / 100;


cout << "Average is " << average
numbers? << endl;
return 0;
}
3

Introduction
Array is a data structure that represents a collection of the
same types of data.

4
Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
5

Declaring Array Variables


datatype arrayRefVar[arraySize];
Example:
double myList[10];

C++ requires that the array size used to declare an array must be a
constant expression. For example, the following code is illegal:
int size = 10;
double myList[size]; // Wrong

But it would be OK, if size is a constant as follow:


const int size = 10;
double myList[size], list2[5]; // Correct
6

6
Arbitrary Initial Values

When an array is created, its elements are assigned


with arbitrary values.
They are not initialized.

Accessing Array Elements


• The array elements are accessed through the index.
Array indices are 0-based; that is, they start from 0 to
arraySize-1.

• Each element in the array is represented using the


following syntax, known as an indexed variable:

arrayName[index];

• For example, myList[9] represents the last element in


the array myList.

8
Using Indexed Variables
• After an array is created, an indexed variable can be
used in the same way as a regular variable.
• Examples:
myList[2] = myList[0] + myList[1];
myList[3]++;
cout << max(myList[0], myList[1]) << endl;
• C++ does not check array’s boundary. So, accessing array
elements using subscripts beyond the boundary (e.g.,
myList[-1] and myList[11]) does not cause syntax
errors, but the operating system might report a memory
access violation.
9

Array Initializers
Declaring, creating, initializing in one step:
dataType arrayName[arraySize] = {value0, value1,
..., valuek};

Examples:
double myList[4] = {1.9, 2.9, 3.4, 3.5};
double myList[] = {1.9, 2.9, 3.4, 3.5};
double myList[4] = {1.9, 2.9};

10

10
animation
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 0
} 2 0
values[0] = values[1] + values[4];
3 0
}
4 0

11

11

animation
Trace Program with Arrays
i becomes 1

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 0
} 2 0
values[0] = values[1] + values[4];
3 0
}
4 0

12

12
animation
Trace Program with Arrays
i (=1) is less than 5

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 0
} 2 0
values[0] = values[1] + values[4];
3 0
}
4 0

13

13

animation
Trace Program with Arrays
After this line is executed, value[1] is 1

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 0
values[0] = values[1] + values[4];
3 0
}
4 0

14

14
animation

Trace Program with Arrays


After i++, i becomes 2

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 0
values[0] = values[1] + values[4];
3 0
}
4 0

15

15

animation
Trace Program with Arrays
i (= 2) is less than 5

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 0
values[0] = values[1] + values[4];
3 0
}
4 0

16

16
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 0
}
4 0

17

17

animation
Trace Program with Arrays
After this, i becomes 3.

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 0
}
4 0

18

18
animation
Trace Program with Arrays
i (=3) is still less than 5.

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 0
}
4 0

19

19

animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 6
}
4 0

20

20
animation
Trace Program with Arrays
After this, i becomes 4

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 6
}
4 0

21

21

animation
Trace Program with Arrays
i (=4) is still less than 5

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 6
}
4 0

22

22
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 6
}
4 10

23

23

animation
Trace Program with Arrays
After i++, i becomes 5

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 6
}
4 10

24

24
animation

Trace Program with Arrays


i ( =5) < 5 is false. Exit the loop

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 0
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 6
}
4 10

25

25

animation
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)

int main()
{ After the array is created
int values[5] = { 0, 0, 0, 0, 0 };
for (int i = 1; i < 5; i++)
0 11
{
values[i] = i + values[i - 1]; 1 1
} 2 3
values[0] = values[1] + values[4];
3 6
}
4 10

26

26
Processing Arrays
• The following loop initializes the array myList with random
values between 0 and 99:
const int ARRAY_SIZE = 10;
double myList[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++)
{
myList[i] = rand() % 100;
}
• Summing all elements:
double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
}
27

27

Printing Arrays
To print an array, you have to print each element in the
array using a loop like the following:

for (int i = 0; i < ARRAY_SIZE; i++)


{
cout << myList[i] << " ";
}

28

28
Copying Arrays
Can you copy array using a syntax like this?
list = myList; // Does not work

This is not allowed in C++. You have to copy individual


elements from one array to the other as follows:

for (int i = 0; i < ARRAY_SIZE; i++)


{
list[i] = myList[i];
}

29

29

Finding the Largest Element


• Use a variable named max to store the largest element.
Initially max is myList[0].
• To find the largest element in the array myList,
compare each element in myList with max, update max
if the element is greater than max.
double max = myList[0];
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
max = myList[i];
}
30

30
Finding the Smallest Index of
the Largest Element
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
}
31

31

Shifting/Rotating Elements
double temp = myList[0]; // Save the first
// Shift elements up
for (int i = 1; i < ARRAY_SIZE; i++)
{
myList[i - 1] = myList[i];
}
// First element to last position
myList[ARRAY_SIZE - 1] = temp;

32

32
C++11: Foreach loops
are defined in C++11
Foreach Loops

double myList[] = { 0, 1.5, 2.1 };


for (double e : myList) {
cout << e << endl;
}

0
1.5
2.1

33

33

Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
34

34
Problem: Lotto Numbers
supplement

The problem is to write a program that checks if all the


input numbers cover 1 to 99

LottoNumbers Run 35

35

LottoNumbers.cpp 1/2
#include <iostream>
using namespace std;

int main()
{
bool isCovered[99];
int number; // number read from a file

// Initialize the array


for (int i = 0; i < 99; i++)
isCovered[i] = false;

// Read each number and mark its corresponding element


cin >> number;
while (number != 0)
{
isCovered[number - 1] = true;
cin >> number;
}
36

36
LottoNumbers.cpp 2/2
// Check if all covered
bool allCovered = true; // Assume all covered initially
for (int i = 0; i < 99; i++)
if (!isCovered[i])
{
allCovered = false; // Find one number not covered
break;
}

// Display result
if (allCovered)
cout << "The tickets cover all numbers" << endl;
else
cout << "The tickets don't cover all numbers" << endl;

return 0;
}
37

37

Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
38

38
Problem: Deck of Cards
• The problem is to write a program that picks four cards randomly
from a deck of 52 cards.
• All the cards can be represented using an array named deck, filled
with initial values 0 to 52, as follows:

const int NUMBER_OF_CARDS = 52;


int deck[NUMBER_OF_CARDS];

// Initialize cards
for (int i = 0; i < NUMBER_OF_CARDS; i++)
deck[i] = i;

39

39

Problem: Deck of Cards, cont.

DeckOfCards Run

40

40
DeckOfCards.cpp 1/2
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;

int main()
{
const int NUMBER_OF_CARDS = 52;
int deck[NUMBER_OF_CARDS];
string suits[] = { "Spades", "Hearts", "Diamonds", "Clubs" };
string ranks[] = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "Jack", "Queen", "King" };

// Initialize cards
for (int i = 0; i < NUMBER_OF_CARDS; i++)
deck[i] = i;
41

41

DeckOfCards.cpp 2/2
// Shuffle the cards
srand(time(0));
for (int i = 0; i < NUMBER_OF_CARDS; i++)
{
// Generate an index randomly
int index = rand() % NUMBER_OF_CARDS;
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}

// Display the first four cards


for (int i = 0; i < 4; i++)
{
string suit = suits[deck[i] / 13];
string rank = ranks[deck[i] % 13];
cout << "Card number " << deck[i] << ": "
<< rank << " of " << suit << endl;
}

return 0;
} 42

42
Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
43

43

Passing Arrays to Functions


• You can pass an entire array to a function.
• You need also to pass the size of the array.
• This program gives an example to demonstrate
how to declare and invoke this type of
functions.

PassArrayDemo Run

44

44
PassArrayDemo.cpp
#include <iostream>
using namespace std;

void printArray(int list[], int arraySize); // Prototype

int main()
{
int numbers[6] = { 1, 4, 3, 6, 8, 9 };
printArray(numbers, 6); // Invoke the function

return 0;
}

void printArray(int list[], int arraySize)


{
for (int i = 0; i < arraySize; i++)
{
cout << list[i] << " "; 1 4 3 6 8 9
}
}
45

45

Pass-by-Value
• Passing an array variable means that the starting
address of the array is passed to the formal
parameter by value.
• The parameter inside the function references to
the same array that is passed to the function. No
new arrays are created.

EffectOfPassArrayDemo Run

46

46
EffectOfPassArrayDemo.cpp
#include <iostream>
using namespace std;

void m(int, int[]);

int main()
{
int x = 1; // x represents an int value
int y[10] = { 0 }; // y represents an array of int values

m(x, y); // Invoke m with arguments x and y

cout << "x is " << x << endl;


cout << "y[0] is " << y[0] << endl;

return 0;
}

void m(int number, int numbers[])


{
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
47

47

Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
48

48
Preventing Changes of Array
Arguments in Functions
• Passing arrays by reference makes sense for
performance reasons. If an array is passed by value, all
its elements must be copied into a new array.
• However, passing arrays by its reference value could lead
to errors if your function changes the array accidentally.
• To prevent it from happening, you can put the const to
tell the compiler that the array cannot be changed.
• The compiler will report errors if the code in the
function attempts to modify the array.

ConstArrayDemo Compile error


49

49

ConstArrayDemo.cpp
#include <iostream>
using namespace std;

void p(int const list[], int arraySize)


{
// Modify array accidentally
list[0] = 100; // Compile error!
} 1>C:\ConstArrayDemo.cpp(7,18): error C3892: 'list': you cannot assign to a
variable that is const
1>Done building project "Testing.vcxproj" -- FAILED.
int main() ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
{
int numbers[5] = {1, 4, 3, 6, 8};
p(numbers, 5);

return 0;
}
50

50
Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
51

51

Returning Arrays from Functions

• How to return an array from a function?


• You may attempt to declare a function that returns a new
array that is a reversal of an array as follows:

// Return the reversal of list


int[] reverse(const int list[], int size);

• This is not allowed in C++.

52

52
Returning Arrays from Functions,
cont.
• However, you can pass two array arguments in the
function, as follows:
// newList is the reversal of list
void reverse(const int list[], int newList[],
int size);

ReverseArray Run

53

53

ReverseArray.cpp 1/2
#include <iostream>
using namespace std;

// newList is the reversal of list


void reverse(const int list[], int newList[], int size)
{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

void printArray(const int list[], int size)


{
for (int i = 0; i < size; i++)
cout << list[i] << " ";
} 54

54
ReverseArray.cpp 1/2
int main()
{
const int SIZE = 6;
int list[] = { 1, 2, 3, 4, 5, 6 };
int newList[SIZE];

reverse(list, newList, SIZE);

cout << "The original array: ";


printArray(list, SIZE);
cout << endl;

cout << "The reversed array: ";


printArray(newList, SIZE);
cout << endl;

return 0;
} 55

55

animation

Trace the reverse Function


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

1 2 3 4 5 6
list

newList 0 0 0 0 0 0

56

56
animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE); i = 0 and j = 5

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

1 2 3 4 5 6
list

newList 0 0 0 0 0 0

57

57

animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 }; i (= 0) is less than 6
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

1 2 3 4 5 6
list

newList 0 0 0 0 0 0

58

58
animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 0 and j = 5
Assign list[0] to result[5]
}

1 2 3 4 5 6
list

newList 0 0 0 0 0 1

59

59

animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 1 and j
} becomes 4

1 2 3 4 5 6
list

newList 0 0 0 0 0 1

60

60
animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);
i (=1) is less than 6
void reverse(const int list[], int newList[], int size)
{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

1 2 3 4 5 6
list

newList 0 0 0 0 0 1

61

61

animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
} i = 1 and j = 4
Assign list[1] to result[4]

1 2 3 4 5 6
list

newList 0 0 0 0 2 1

62

62
animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 2 and
} j becomes 3

1 2 3 4 5 6
list

newList 0 0 0 0 2 1

63

63

animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i (=2) is still less than 6
}
}

1 2 3 4 5 6
list

newList 0 0 0 0 2 1

64

64
animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 2 and j = 3
} Assign list[i] to result[j]

1 2 3 4 5 6
list

newList 0 0 0 3 2 1

65

65

animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
After this, i becomes 3 and
} j becomes 2
}

1 2 3 4 5 6
list

newList 0 0 0 3 2 1

66

66
animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
} i (=3) is still less than 6

1 2 3 4 5 6
list

newList 0 0 0 3 2 1

67

67

animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 3 and j = 2
} Assign list[i] to result[j]

1 2 3 4 5 6
list

newList 0 0 4 3 2 1

68

68
animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
After this, i becomes 4 and
} j becomes 1

1 2 3 4 5 6
list

newList 0 0 4 3 2 1

69

69

animation

Trace the reverse Function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
} i (=4) is still less than 6

1 2 3 4 5 6
list

newList 0 0 4 3 2 1

70

70
animation

Trace the reverse Function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i = 4 and j = 1
} Assign list[i] to result[j]
}

1 2 3 4 5 6
list

newList 0 5 4 3 2 1

71

71

animation

Trace the reverse Function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
After this, i becomes 5 and
} j becomes 0

1 2 3 4 5 6
list

newList 0 5 4 3 2 1

72

72
animation

Trace the reverse Function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
i (=5) is still less than 6
}

1 2 3 4 5 6
list

newList 0 5 4 3 2 1

73

73

animation

Trace the reverse Function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 5 and j = 0
Assign list[i] to result[j]
}

1 2 3 4 5 6
list

newList 6 5 4 3 2 1

74

74
animation

Trace the reverse Function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
After this, i becomes 6 and
} j becomes -1
}

1 2 3 4 5 6
list

newList 6 5 4 3 2 1

75

75

animation

Trace the reverse function, cont.


int list[] = { 1, 2, 3, 4, 5, 6 };
reverse(list, newList, SIZE);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i (=6) < 6 is false. So exit
} the loop.
}

1 2 3 4 5 6
list

newList 6 5 4 3 2 1

76

76
Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
77

77

C-Strings
• You studied the string type in Chapter 4.
• Example:
string s = "welcome to C++";
s.at(0) = 'W';
cout << s.length() << s[0] << endl;
14W
• Here we study the older C-strings because of
their popularity.

78

78
Initializing Character Arrays
• You can define arrays of characters.
char city[] = { 'D', 'a', 'l', 'l', 'a', 's' };
• C-strings are defined as follows:
char city[] = "Dallas";
• In this case, C++ adds the character '\0', called the null
terminator, to indicate the end of the string.

79

79

Reading C-Strings
You can read a string from the keyboard using the
cin object. For example, see the following code:

char city[10];
cout << "Enter a city: ";
cin >> city; // read to array city
cout << "You entered " << city << endl;

80

80
Printing Character Array
For a character array, it can be printed using one print
statement. For example, the following code displays Dallas:

char city[] = "Dallas";


cout << city;

81

81

Reading C-Strings Using getline


• C++ provides the cin.getline function in the iostream
header file, which reads a string into an array:
cin.getline(char array[], int size, char delimitChar);
• The function stops reading characters when the
delimiter character is encountered or when the size -
1 number of characters are read.
• The last character in the array is reserved for the null
terminator ('\0').
• If the delimiter is encountered, it is read, but not stored
in the array.
• The third argument delimitChar has a default value
('\n').
82

82
Working with C-Strings
• The following function finds the length of a C-
string:
unsigned int strlen(char s[])
{
for (int i = 0; s[i] != '\0'; i++)
;
return i;
}
• The cstring and cstdlib headers provide
many useful C-strings functions.
83

83

C-String Functions

84

84
C-String Examples

CopyString Run

CombineString Run

CompareString Run

StringConversion Run

85

85

CopyString.CPP
#include <iostream>
#include <cstring>
The string in s1 is Dallas, Texas
using namespace std;
The string in s2 is Dallas, Texas
int main() The string in s3 is Dallas
{ The length of string s3 is 6
char s1[20];
char s2[20] = "Dallas, Texas";
char s3[20] = "AAAAAAAAAA";

strcpy(s1, s2);
strncpy(s3, s2, 6);
s3[6] = '\0'; // Insert null terminator

cout << "The string in s1 is " << s1 << endl;


cout << "The string in s2 is " << s2 << endl;
cout << "The string in s3 is " << s3 << endl;
cout << "The length of string s3 is " << strlen(s3) << endl;

return 0;
86
}

86
CombineString.cpp
#include <iostream> The string in s1 is Dallas, Texas, USA
#include <cstring> The string in s2 is Texas, USA
using namespace std; The string in s3 is Dallas, Texas
The length of string s1 is 18
int main()
The length of string s3 is 13
{
char s1[20] = "Dallas";
char s2[20] = "Texas, USA";
char s3[20] = "Dallas";

strcat(strcat(s1, ", "), s2);


strncat(strcat(s3, ", "), s2, 5);

cout << "The string in s1 is " << s1 << endl;


cout << "The string in s2 is " << s2 << endl;
cout << "The string in s3 is " << s3 << endl;
cout << "The length of string s1 is " << strlen(s1) << endl;
cout << "The length of string s3 is " << strlen(s3) << endl;

return 0;
87
}

87

CompareString.cpp
#include <iostream>
#include <cstring> strcmp(s1, s2) is -1
using namespace std; strcmp(s2, s1) is 1
strcmp(s2, s3) is 0
int main()
strncmp(s1, s2, 3) is 0
{
char s1[] = "abcdefg";
char s2[] = "abcdg";
char s3[] = "abcdg";

cout << "strcmp(s1, s2) is " << strcmp(s1, s2) << endl;
cout << "strcmp(s2, s1) is " << strcmp(s2, s1) << endl;
cout << "strcmp(s2, s3) is " << strcmp(s2, s3) << endl;
cout << "strncmp(s1, s2, 3) is " << strncmp(s1, s2, 3)
<< endl;

return 0;
}

88

88
StringConversion.cpp
#include <iostream>
#include <cstring>
using namespace std; 9
10
int main() 52
{ 42
cout << atoi("4") + atoi("5") << endl; 2a
cout << atof("4.5") + atof("5.5") << endl;

char s[10];
itoa(42, s, 8);
cout << s << endl;

itoa(42, s, 10);
cout << s << endl;

itoa(42, s, 16);
cout << s << endl;

return 0;
} 89

89

Converting Numbers to Strings


• Note that the to_string function is useful to convert numbers to string
type.
#include <iostream>
#include <string>
using namespace std; C++11: the to_string function
is defined in C++11
int main()
{
int x = 15;
double y = 1.32;
long long int z = 10935;
string s = "Three numbers: " + to_string(x) + ", " +
to_string(y) + ", and " + to_string(z);
cout << s << endl;

return 0;
}
Three numbers: 15, 1.320000, and 10935
90

90
Outline
• Introduction
• Array Basics
• Problem: Lotto Numbers
• Problem: Deck of Cards
• Passing Arrays to Functions
• Preventing Changes of Array Arguments in
Functions
• Returning Arrays from Functions
• C-Strings
91

91
Chapter 8: Multidimensional
Arrays

Sections 8.1-8.5, 8.8

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline

• Introduction
• Declaring Two-Dimensional Arrays
• Processing Two-Dimensional Arrays
• Passing Two-Dimensional Arrays to Functions
• Problem: Grading a Multiple-Choice Test
• Multidimensional Arrays

2
Introduction
Data in a table or a matrix can be represented
using a two-dimensional array.

Outline

• Introduction
• Declaring Two-Dimensional Arrays
• Processing Two-Dimensional Arrays
• Passing Two-Dimensional Arrays to Functions
• Problem: Grading a Multiple-Choice Test
• Multidimensional Arrays

4
Declaring Two-Dimensional
Arrays
elementType arrayName[ROW_SIZE][COLUMN_SIZE];

• Example
int distances[7][7];

• An element in a two-dimensional array is


accessed through a row and column index.
int bostonToDalas = distances[1][5];

Two-Dimensional Array Illustration

6
Outline

• Introduction
• Declaring Two-Dimensional Arrays
• Processing Two-Dimensional Arrays
• Passing Two-Dimensional Arrays to Functions
• Problem: Grading a Multiple-Choice Test
• Multidimensional Arrays

Initializing Arrays with Random


Values
• Nested for loops are often used to process a two-
dimensional array.
• The following loop initializes the array with random
values between 0 and 99:

for (int row = 0; row < rowSize; row++)


{
for (int column = 0; column < columnSize; column++)
{
matrix[row][column] = rand() % 100;
}
}

8
Printing Arrays
• To print a two-dimensional array, you have to print each
element in the array using a loop like the following:

for (int row = 0; row < rowSize; row++)


{
for (int column = 0; column < columnSize; column++)
{
cout << matrix[row][column] << " ";
}
cout << endl;
}

Summing All Elements


• To sum all elements of a two-dimensional array:

int total = 0;
for (int row = 0; row < ROW_SIZE; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
total += matrix[row][column];
}
}

10

10
Summing Elements by Column
• For each column, use a variable named total to store
its sum. Add each element in the column to total
using a loop like this:

for (int column = 0; column < columnSize; column++)


{
int total = 0;
for (int row = 0; row < rowSize; row++)
total += matrix[row][column];
cout << "Sum for column " << column << " is “
<< total << endl;
}

11

11

Which row has the largest sum?


• Use variables maxRow and indexOfMaxRow to track the largest sum and index
of the row. For each row, compute its sum and update maxRow and
indexOfMaxRow if the new sum is greater.
int maxRow = 0;
int indexOfMaxRow = 0;
// Get sum of the first row in maxRow
for (int column = 0; column < COLUMN_SIZE; column++)
maxRow += matrix[0][column];
for (int row = 1; row < ROW_SIZE; row++)
{
int totalOfThisRow = 0;
for (int column = 0; column < COLUMN_SIZE; column++)
totalOfThisRow += matrix[row][column];
if (totalOfThisRow > maxRow)
{
maxRow = totalOfThisRow;
indexOfMaxRow = row;
}
}
cout << "Row " << indexOfMaxRow
<< " has the maximum sum of " << maxRow << endl; 12

12
Outline

• Introduction
• Declaring Two-Dimensional Arrays
• Processing Two-Dimensional Arrays
• Passing Two-Dimensional Arrays to Functions
• Problem: Grading a Multiple-Choice Test
• Multidimensional Arrays

13

13

Passing Two-Dimensional Arrays


to Functions
• You can pass a two-dimensional array to a function.
• The column size to be specified in the function
declaration.
• A program that for a function that returns the sum
of all the elements in a matrix.

PassTwoDimensionalArray Run

14

14
PassTwoDimensionalArray.cpp 1/2
#include <iostream>
using namespace std;

const int COLUMN_SIZE = 4;

int sum(const int a[][COLUMN_SIZE], int rowSize)


{
int total = 0;
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
total += a[row][column];
}
}

return total;
}

15

15

PassTwoDimensionalArray.cpp 2/2
int main()
{
const int ROW_SIZE = 3;
int m[ROW_SIZE][COLUMN_SIZE];

cout << "Enter " << ROW_SIZE << " rows and "
<< COLUMN_SIZE << " columns: " << endl;
for (int i = 0; i < ROW_SIZE; i++)
for (int j = 0; j < COLUMN_SIZE; j++)
cin >> m[i][j];

cout << "\nSum of all elements is " << sum(m, ROW_SIZE)


<< endl;

return 0;
}

16

16
Outline

• Introduction
• Declaring Two-Dimensional Arrays
• Processing Two-Dimensional Arrays
• Passing Two-Dimensional Arrays to Functions
• Problem: Grading a Multiple-Choice Test
• Multidimensional Arrays

17

17

Problem: Grading Multiple-Choice Test

GradeExam Run

18

18
GradeExam.cpp 1/2
#include <iostream>
using namespace std;

int main()
{
const int NUMBER_OF_STUDENTS = 8;
const int NUMBER_OF_QUESTIONS = 10;

// Students' answers to the questions


char answers[NUMBER_OF_STUDENTS][NUMBER_OF_QUESTIONS] =
{
{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},
{'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'},
{'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'},
{'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}
}; 19

19

GradeExam.cpp 2/2
// Key to the questions
char keys[] = { 'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D' };

// Grade all answers


for (int i = 0; i < NUMBER_OF_STUDENTS; i++)
{
// Grade one student
int correctCount = 0;
for (int j = 0; j < NUMBER_OF_QUESTIONS; j++)
{
if (answers[i][j] == keys[j])
correctCount++;
}

cout << "Student " << i << "'s correct count is " <<
correctCount << endl;
}

return 0;
} 20

20
Outline

• Introduction
• Declaring Two-Dimensional Arrays
• Processing Two-Dimensional Arrays
• Passing Two-Dimensional Arrays to Functions
• Problem: Grading a Multiple-Choice Test
• Multidimensional Arrays

21

21

Multidimensional Arrays
You can create n-dimensional arrays for any integer n.

For example, you may use a three-dimensional array to store exam


scores for a class of 6 students with 5 exams and each exam has 2
parts (multiple-choice and essay).
double scores[6][5][2];

With initialization:
double scores[6][5][2] = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}} };22

22
Problem: Daily Temperature and
Humidity
• Suppose a meteorology station records the temperature
and humidity at each hour of every day and stores the
data for the past ten days in a text file named
weather.txt.
• Each line of the file consists of four numbers that
indicates the day, hour, temperature, and humidity.

A program that calculates the average


daily temperature and humidity for the 10 Weather Run
days. 23

23

Weather.cpp 1/2
#include <iostream>
using namespace std;

int main()
{
const int NUMBER_OF_DAYS = 10;
const int NUMBER_OF_HOURS = 24;
double data[NUMBER_OF_DAYS][NUMBER_OF_HOURS][2];

// Read input using input redirection from a file


int day, hour;
double temperature, humidity;
for (int k = 0; k < NUMBER_OF_DAYS * NUMBER_OF_HOURS; k++)
{
cin >> day >> hour >> temperature >> humidity;
data[day - 1][hour - 1][0] = temperature;
data[day - 1][hour - 1][1] = humidity;
} 24

24
Weather.cpp 2/2
// Find the average daily temperature and humidity
for (int i = 0; i < NUMBER_OF_DAYS; i++)
{
double dailyTemperatureTotal = 0, dailyHumidityTotal = 0;
for (int j = 0; j < NUMBER_OF_HOURS; j++)
{
dailyTemperatureTotal += data[i][j][0];
dailyHumidityTotal += data[i][j][1];
}

// Display result
cout << "Day " << i << "'s average temperature is "
<< dailyTemperatureTotal / NUMBER_OF_HOURS << endl;
cout << "Day " << i << "'s average humidity is "
<< dailyHumidityTotal / NUMBER_OF_HOURS << endl;
}

return 0;
}
25

25

Problem: Guessing Birthday


• Listing 4.4, GuessBirthday.cpp, gives a
program that guesses a birthday.
• The program can be simplified by storing the
numbers in five sets in a three-dimensional
array, and it prompts the user for the answers
using a loop.

GuessBirthdayUsingArray Run

26

26
GuessBirthdayUsingArray.cpp 1/2
int dates[5][4][4] = {
{{ 1, 3, 5, 7},
#include <iostream> { 9, 11, 13, 15},
{17, 19, 21, 23},
#include <iomanip>
{25, 27, 29, 31}},
using namespace std; {{ 2, 3, 6, 7},
{10, 11, 14, 15},
int main() {18, 19, 22, 23},
{ {26, 27, 30, 31}},
{{ 4, 5, 6, 7},
int day = 0; // Day to be determined
{12, 13, 14, 15},
char answer; {20, 21, 22, 23},
{28, 29, 30, 31}},
{{ 8, 9, 10, 11},
{12, 13, 14, 15},
{24, 25, 26, 27},
{28, 29, 30, 31}},
{{16, 17, 18, 19},
{20, 21, 22, 23},
{24, 25, 26, 27},
{28, 29, 30, 31}} };

27

27

GuessBirthdayUsingArray.cpp 1/2
for (int i = 0; i < 5; i++)
{
cout << "Is your birthday in Set" << (i + 1) << "?" << endl;
for (int j = 0; j < 4; j++)
{
for (int k = 0; k < 4; k++)
cout << setw(3) << dates[i][j][k] << " ";
cout << endl;
}
cout << "\nEnter N/n for No and Y/y for Yes: ";
cin >> answer;
if (answer == 'Y' || answer == 'y')
day += dates[i][0][0];
}

cout << "Your birthday is " << day << endl;

return 0;
}
28

28
Outline

• Introduction
• Declaring Two-Dimensional Arrays
• Processing Two-Dimensional Arrays
• Passing Two-Dimensional Arrays to Functions
• Problem: Grading a Multiple-Choice Test
• Multidimensional Arrays

29

29
1/29/20

Chapter 17: Recursion

Sections 17.1-17.2

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline

• Introduction
• Example: Factorials

1
1/29/20

Motivations
• Recursion is a technique that leads to elegant
solutions to problems that are difficult to
program using simple loops.
• A recursive function is one that invokes itself.
• Suppose you want to find all the files under a
directory that contains a particular word. How
do you solve this problem? There are several
ways to solve this problem. An intuitive solution
is to use recursion by searching the files in the
subdirectories recursively.
3

Outline

• Introduction
• Example: Factorials

2
1/29/20

Computing Factorial
n! = n × (n - 1) × (n - 2) × ... × 2 × 1

0! = 1;
n! = n × (n - 1)!; n > 0

factorial(0) = 1;
factorial(n) = n*factorial(n-1);

ComputeFactorial Run

ComputeFactorial.cpp
#include <iostream>
using namespace std;

// Return the factorial for a specified index


long long factorial(int n)
{
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}

int main()
{
// Prompt the user to enter an integer
cout << "Please enter a non-negative integer: ";
int n;
cin >> n;

// Display factorial
cout << "Factorial of " << n << " is " << factorial(n);

return 0;
}
Factorial of 4 is 24 6

3
1/29/20

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4)

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)

4
1/29/20

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))

10

10

5
1/29/20

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))

11

11

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))

12

12

6
1/29/20

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))
= 4 * 3 * ( 2 * 1)

13

13

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))
= 4 * 3 * ( 2 * 1)
=4*3*2

14

14

7
1/29/20

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))
= 4 * 3 * ( 2 * 1)
=4*3*2
=4*6

15

15

animation

Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))
= 4 * 3 * ( 2 * 1)
=4*3*2
=4*6
= 24
16

16

8
1/29/20

animation

Trace Recursive factorial


Executes factorial(4)

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
Space Required
return 2 * factorial(1) for factorial(2)
4 Space Required
for factorial(1)
Step 3: executes factorial(1)
Step 6: return 1 3 Space Required
for factorial(2)

return 1 * factorial(0) Space Required


for factorial(3)
Space Required
for factorial(3)

Step 4: executes factorial(0) Space Required


Step 5: return 1 Space Required
for factorial(4)
for factorial(4)

return 1 Main function

17

17

animation

Trace Recursive factorial

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24 Executes factorial(3)
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
5
Space Required
return 2 * factorial(1) for factorial(2)
4 Space Required
for factorial(1)

Step 3: executes factorial(1) 3 Space Required


Step 6: return 1 for factorial(2)
Space Required Space Required
return 1 * factorial(0) Space Required
for factorial(3)
for factorial(3) for factorial(3)
Space Required
Step 4: executes factorial(0) Space Required for factorial(4)

Step 5: return 1 for factorial(4)


Main function
return 1

18

18

9
1/29/20

animation

Trace Recursive factorial

factorial(4) Executes factorial(2)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
5
Space Required
return 2 * factorial(1) for factorial(2)
4 Space Required
for factorial(1)

Step 3: executes factorial(1) 3 Space Required


Step 6: return 1 Space Required for factorial(2)
for factorial(2) Space Required Space Required
return 1 * factorial(0) Space Required
for factorial(3)
for factorial(3) for factorial(3)
Space Required
Step 4: executes factorial(0) Space Required for factorial(4)

Step 5: return 1 for factorial(4)


Main function
return 1

19

19

animation

Trace Recursive factorial

factorial(4) Executes factorial(1)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
Space Required
return 2 * factorial(1) for factorial(2)
4 Space Required
Space Required for factorial(1)
Step 3: executes factorial(1) for factorial(1)
Step 6: return 1 Space Required
3 Space Required
for factorial(2)
for factorial(2)
return 1 * factorial(0) Space Required
Space Required
for factorial(3)
Space Required
for factorial(3)
for factorial(3)
Step 4: executes factorial(0) Space Required
Step 5: return 1 Space Required
for factorial(4)
for factorial(4)

return 1 Main function

20

20

10
1/29/20

animation

Trace Recursive factorial

factorial(4) Executes factorial(0)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
Space Required
return 2 * factorial(1) Space Required
for factorial(0)
for factorial(2)
4 Space Required
Space Required for factorial(1)
Step 3: executes factorial(1) for factorial(1)
Step 6: return 1 Space Required
3 Space Required
for factorial(2)
for factorial(2)
return 1 * factorial(0) Space Required
Space Required
for factorial(3)
Space Required
for factorial(3)
for factorial(3)
Step 4: executes factorial(0) Space Required
Step 5: return 1 Space Required
for factorial(4)
for factorial(4)

return 1 Main function

21

21

animation

Trace Recursive factorial

factorial(4) returns 1
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
5
Space Required
Space Required
return 2 * factorial(1) for factorial(0)
for factorial(2)
4 Space Required
Space Required for factorial(1)

Step 3: executes factorial(1) for factorial(1)


3 Space Required
Step 6: return 1 Space Required for factorial(2)
for factorial(2) Space Required Space Required
return 1 * factorial(0) Space Required for factorial(3) for factorial(3)
for factorial(3) Space Required
Step 4: executes factorial(0) Space Required for factorial(4)
Step 5: return 1 for factorial(4)
Main function
return 1

22

22

11
1/29/20

animation

Trace Recursive factorial

factorial(4) returns factorial(0)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
Space Required
return 2 * factorial(1) Space Required
for factorial(0)
for factorial(2)
4 Space Required
Space Required for factorial(1)
Step 3: executes factorial(1)
Step 6: return 1 for factorial(1)
3 Space Required
for factorial(2)
Space Required
for factorial(2)
return 1 * factorial(0) Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
Step 4: executes factorial(0) for factorial(3) Space Required
Step 5: return 1 Space Required for factorial(4)
for factorial(4)
return 1 Main function

23

23

animation

Trace Recursive factorial

factorial(4) returns factorial(1)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
Space Required
return 2 * factorial(1) for factorial(2)
4 Space Required
Space Required for factorial(1)
Step 3: executes factorial(1)
Step 6: return 1 for factorial(1)
3 Space Required
for factorial(2)
Space Required
for factorial(2)
return 1 * factorial(0) Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
Step 4: executes factorial(0) for factorial(3) Space Required
Step 5: return 1 Space Required for factorial(4)
for factorial(4)
return 1 Main function

24

24

12
1/29/20

animation

Trace Recursive factorial

factorial(4) returns factorial(2)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
Space Required
return 2 * factorial(1) for factorial(2)
4 Space Required
for factorial(1)
Step 3: executes factorial(1)
Step 6: return 1 3 Space Required
for factorial(2)
Space Required
for factorial(2)
return 1 * factorial(0) Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
Step 4: executes factorial(0) for factorial(3) Space Required
Step 5: return 1 Space Required for factorial(4)
for factorial(4)
return 1 Main function

25

25

animation

Trace Recursive factorial

factorial(4) returns factorial(3)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
Space Required
return 2 * factorial(1) for factorial(2)
4 Space Required
for factorial(1)
Step 3: executes factorial(1)
Step 6: return 1 3 Space Required
for factorial(2)

return 1 * factorial(0) Space Required


for factorial(3)
Space Required
for factorial(3)
Space Required
Step 4: executes factorial(0) for factorial(3) Space Required
Step 5: return 1 Space Required for factorial(4)
for factorial(4)
return 1 Main function

26

26

13
1/29/20

animation

Trace Recursive factorial


returns factorial(4)

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
Space Required
return 2 * factorial(1) for factorial(2)
4 Space Required
for factorial(1)
Step 3: executes factorial(1)
Step 6: return 1 3 Space Required
for factorial(2)

return 1 * factorial(0) Space Required


for factorial(3)
Space Required
for factorial(3)

Step 4: executes factorial(0) Space Required


Step 5: return 1 Space Required for factorial(4)
for factorial(4)
return 1 Main function

27

27

factorial(4) Stack Trace

28

28

14
1/29/20

Outline

• Introduction
• Example: Factorials

29

29

15
Chapter 9: Objects and Classes

Sections 9.1-9.6, 9.9

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline
• Introduction
• Defining Classes for Objects
• Example: Defining Classes and Creating Objects
• Constructors
• Constructing and Using Objects
• Separating Class Definition from Implementation
• Data Field Encapsulation

2
Introduction
• Object-oriented programming (OOP) involves
programming using objects.
• An object represents an entity in the real world that
can be distinctly identified. For example, a student, a
desk, a circle, a button, and even a loan can all be
viewed as objects.
• An object has a unique identity, state, and behaviors.
• The state of an object consists of a set of data fields
(also known as properties) with their current values.
• The behavior of an object is defined by a set of
functions.
3

Outline
• Introduction
• Defining Classes for Objects
• Example: Defining Classes and Creating Objects
• Constructors
• Constructing and Using Objects
• Separating Class Definition from Implementation
• Data Field Encapsulation

4
Classes and Objects
A class defines the properties and behaviors for
objects..

Classes

• Classes are constructs that define objects of the


same type.
• A class uses variables to define data fields and
functions to define behaviors.
• Additionally, a class provides a special type of
functions, known as constructors, which are
invoked to construct objects from the class.

6
Example of the class for Circle objects

UML Class Diagram

8
class Replaces struct
• The C language has the struct type for representing
records.
• For example, you may define a struct type for
representing students as shown in (a).
• C++ class allows functions in addition to data fields.
class replaces struct, as in (b)
struct Student class Student
{ {
int id; public:
char firstName[30]; int id;
char mi; char firstName[30];
char lastName[30]; char mi;
}; char lastName[30];
};
(a) (b) 9

Outline
• Introduction
• Defining Classes for Objects
• Example: Defining Classes and Creating Objects
• Constructors
• Constructing and Using Objects
• Separating Class Definition from Implementation
• Data Field Encapsulation

10

10
A Simple Circle Class

• Objective: Demonstrate creating


objects, accessing data, and using
functions.

TestCircle Run

11

11

TestCircle.cpp 1/2
#include <iostream>
using namespace std;
// Return the area of this circle
class Circle double getArea()
{ {
public: return radius * radius * 3.14159;
// The radius of this circle }
double radius;
// Return the perimeter of this circle
// Construct a default object double getPermeter()
Circle() {
{ return 2 * radius * 3.14159;
radius = 1; }
}
// Set new radius for this circle
// Construct a circle object void setRadius(double newRadius)
Circle(double newRadius) {
{ radius = newRadius;
radius = newRadius; }
} }; // Must place a semicolon here
12

12
TestCircle.cpp 2/2
int main()
{
Circle circle1(1.0);
Circle circle2(25);
Circle circle3(125);

cout << "The area of the circle of radius "


<< circle1.radius << " is " << circle1.getArea() << endl;
cout << "The area of the circle of radius "
<< circle2.radius << " is " << circle2.getArea() << endl;
cout << "The area of the circle of radius "
<< circle3.radius << " is " << circle3.getArea() << endl;

// Modify circle radius


circle2.radius = 100;
cout << "The area of the circle of radius "
<< circle2.radius << " is " << circle2.getArea() << endl;
The area of the circle of radius 1 is 3.14159
return 0;
The area of the circle of radius 25 is 1963.49
} The area of the circle of radius 125 is 49087.3
The area of the circle of radius 100 is 31415.9 13

13

Example: The TV class models TV sets

TV Run
14

14
TV.cpp 1/4
#include <iostream>
using namespace std;

class TV
{
public:
int channel;
int volumeLevel; // Default volume level is 1
bool on; // By default TV is off

TV()
{
channel = 1; // Default channel is 1
volumeLevel = 1; // Default volume level is 1
on = false; // By default TV is off
}

void turnOn()
{
on = true;
} 15

15

TV.cpp 2/4
void turnOff()
{
on = false;
}

void setChannel(int newChannel)


{
if (on && newChannel >= 1 && newChannel <= 120)
channel = newChannel;
}

void setVolume(int newVolumeLevel)


{
if (on && newVolumeLevel >= 1 && newVolumeLevel <= 7)
volumeLevel = newVolumeLevel;
}

void channelUp()
{
if (on && channel < 120)
channel++;
} 16

16
TV.cpp 3/4
void channelDown()
{
if (on && channel > 1)
channel--;
}

void volumeUp()
{
if (on && volumeLevel < 7)
volumeLevel++;
}

void volumeDown()
{
if (on && volumeLevel > 1)
volumeLevel--;
}
};

17

17

TV.cpp 4/4
int main()
{
TV tv1;
tv1.turnOn();
tv1.setChannel(30);
tv1.setVolume(3);

TV tv2;
tv2.turnOn();
tv2.channelUp();
tv2.channelUp();
tv2.volumeUp();

cout << "tv1's channel is " << tv1.channel


<< " and volume level is " << tv1.volumeLevel << endl;
cout << "tv2's channel is " << tv2.channel
<< " and volume level is " << tv2.volumeLevel << endl;

return 0;
}
18

18
Outline
• Introduction
• Defining Classes for Objects
• Example: Defining Classes and Creating Objects
• Constructors
• Constructing and Using Objects
• Separating Class Definition from Implementation
• Data Field Encapsulation

19

19

Constructors
• The constructor has exactly the same name as the defining
class.
• Constructors can be overloaded (i.e., multiple constructors
with the same name but different signatures).
• A class normally provides a constructor without arguments
(e.g., Circle()). Such constructor is called a no-arg or no-
argument constructor.
• A class may be declared without constructors. In this case, a
no-arg constructor with an empty body is implicitly declared
in the class. This constructor is called a default constructor.

20

20
Constructors Features
• Constructors must have the same name as the
class itself.
• Constructors do not have a return type—not
even void.
• Constructors play the role of initializing objects.

21

21

Initializer Lists
• Data fields may be initialized in the constructor using
an initializer list in the following syntax:

• Example:

22

22
Outline
• Introduction
• Defining Classes for Objects
• Example: Defining Classes and Creating Objects
• Constructors
• Constructing and Using Objects
• Separating Class Definition from Implementation
• Data Field Encapsulation

23

23

Object Names
• You can assign a name when creating an object.
• A constructor is invoked when an object is created.
• The syntax to create an object using the no-arg
constructor is:
ClassName objectName;

• For example,
Circle circle1;
• The size of and object depends on its data fields
only.
cout << sizeof(circle1) << endl;;
8
24

24
Constructing with Arguments
• The syntax to declare an object using a constructor
with arguments is:

ClassName objectName(arguments);

• For example, the following declaration creates an


object named circle2 by invoking the Circle
class’s constructor with a specified radius 5.5.

Circle circle2(5.5);

25

25

Access Operator
• After an object is created, its data can be
accessed and its functions invoked using the dot
operator (.), also known as the object member
access operator:

• objectName.dataField references a data


field in the object.

• objectName.function(arguments)
invokes a function on the object.
26

26
Naming Objects and Classes
• When you declare a custom class, capitalize the
first letter of each word in a class name; for
example, the class names Circle,
Rectangle, and Desk.
• The class names in the C++ library are named
in lowercase.
• The objects are named like variables.

27

27

Class is a Type

• You can use primitive data types, like int,


to declare variables.
• You can also use class names to declare
object names.
• In this sense, a class is also a data type.

28

28
Memberwise Copy
• You can also use the assignment operator = to copy the
contents from one object to the other.
• By default, each data field of one object is copied to its
counterpart in the other object. For example,

circle2 = circle1;

• Copies the radius in circle1 to circle2.


• After the copy, circle1 and circle2 are still two
different objects, but with the same radius.

29

29

Constant Object Name

• Object names are like array names. Once an


object name is declared, it represents an object.
• It cannot be reassigned to represent another
object.
• In this sense, an object name is a constant,
though the contents of the object may change.

30

30
Anonymous Object
• Most of the time, you create a named object and later
access the members of the object through its name.
• Occasionally, you may create an object and use it only
once. In this case, you don’t have to name the object.
Such objects are called anonymous objects.
• The syntax to create an anonymous object is
ClassName() or ClassName(arguements)
• You can create an anonymous object just for finding the
area by:
cout << "Area:" << Circle(5).getArea() << endl;

31

31

Outline
• Introduction
• Defining Classes for Objects
• Example: Defining Classes and Creating Objects
• Constructors
• Constructing and Using Objects
• Separating Class Definition from Implementation
• Data Field Encapsulation

32

32
Separating Definition from
Implementation
• C++ allows you to separate class definition from
implementation.
• The class definition describes the contract of the class and
the class implementation implements the contract.
• The class declaration simply lists all the data fields,
constructor prototypes, and the function prototypes.
• The class implementation implements the constructors and
functions.
• The class declaration and implementation are in two
separate files. Both files should have the same name, but
with different extension names. The class declaration file
has an extension name .h and the class implementation file
has an extension name .cpp.

Circle.h Circle.cpp TestCircleWithHeader.cpp Run

33

33

Circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
class Circle
Used to prevent a header file from
{ being included multiple times.
public:
// The radius of this circle
double radius;

// Construct a default circle object


Circle();

// Construct a circle object


Circle(double);

// Return the area of this circle


double getArea();
};
#endif 34

34
Circle.cpp
#include "Circle.h"

// Construct a default circle object


Circle::Circle()
{
radius = 1;
} The :: symbol is the binary scope
resolution operator
// Construct a circle object
Circle::Circle(double newRadius)
{
radius = newRadius;
}

// Return the area of this circle


double Circle::getArea()
{
return radius * radius * 3.14159;
} 35

35

TestCircleWithHeader.cpp
#include <iostream>
#include "Circle.h"
using namespace std;
The area of the circle of radius 1 is 3.14159
int main() The area of the circle of radius 5 is 78.5397
{ The area of the circle of radius 100 is 31415.9
Circle circle1;
Circle circle2(5.0);

cout << "The area of the circle of radius "


<< circle1.radius << " is " << circle1.getArea() << endl;
cout << "The area of the circle of radius "
<< circle2.radius << " is " << circle2.getArea() << endl;

// Modify circle radius


circle2.radius = 100;
cout << "The area of the circle of radius "
<< circle2.radius << " is " << circle2.getArea() << endl;

return 0;
} 36

36
Outline
• Introduction
• Defining Classes for Objects
• Example: Defining Classes and Creating Objects
• Constructors
• Constructing and Using Objects
• Separating Class Definition from Implementation
• Data Field Encapsulation

37

37

Data Field Encapsulation


The data fields radius in the Circle class can be
modified directly (e.g., circle1.radius = 5).
This is not a good practice for two reasons:
1. Data may be tampered.
2. Second, it makes the class difficult to maintain and
vulnerable to bugs. Suppose you want to modify the
Circle class to ensure that the radius is non-negative
after other programs have already used the class. You
have to change not only the Circle class, but also
the programs (clients) that use the Circle class. This
is because the clients may have modified the radius
directly (e.g., myCircle.radius = -5).
38

38
Accessor and Mutator
• A get function is referred to as a getter (or accessor).
• A get function has the following signature:
returnType getPropertyName()

• If the returnType is bool, the get function should be defined


as follows by convention:
bool isPropertyName()

• A set function is referred to as a setter (or mutator).


• A set function has the following signature:
public void setPropertyName(dataType propertyValue)

39

39

Example: The Circle Class with


Encapsulation

CircleWithPrivateDataFields.h

CircleWithPrivateDataFields.cpp

TestCircleWithPrivateDataFields Run

40

40
CircleWithPrivateDataFields.h
#ifndef CIRCLE_H
#define CIRCLE_H

class Circle
{
public:
Circle();
Circle(double);
double getArea();
double getRadius();
void setRadius(double);

private:
double radius;
};

#endif
41

41

CircleWithPrivateDataFields.cpp
#include "CircleWithPrivateDataFields.h"
// Return the radius of this
// Construct a default circle object
Circle::Circle()
circle
{ double Circle::getRadius()
radius = 1; {
} return radius;
}
// Construct a circle object
Circle::Circle(double newRadius) // Set a new radius
{
void Circle::setRadius(double
radius = newRadius;
} newRadius)
{
// Return the area of this circle radius = (newRadius >= 0)
double Circle::getArea() ? newRadius : 0;
{ }
return radius * radius * 3.14159;
}

42

42
TestCircleWithPrivateDataFields.cpp
#include <iostream>
#include "CircleWithPrivateDataFields.h"
using namespace std;

int main() The area of the circle of radius 1 is 3.14159


{ The area of the circle of radius 5 is 78.5397
Circle circle1; The area of the circle of radius 100 is 31415.9
Circle circle2(5.0);

cout << "The area of the circle of radius "


<< circle1.getRadius() << " is " << circle1.getArea() << endl;
cout << "The area of the circle of radius "
<< circle2.getRadius() << " is " << circle2.getArea() << endl;

// Modify circle radius


circle2.setRadius(100);
cout << "The area of the circle of radius "
<< circle2.getRadius() << " is " << circle2.getArea() << endl;

return 0;
} 43

43

Outline
• Introduction
• Defining Classes for Objects
• Example: Defining Classes and Creating Objects
• Constructors
• Constructing and Using Objects
• Separating Class Definition from Implementation
• Data Field Encapsulation

44

44
Chapter 11: Pointers and Dynamic
Memory Management

Sections 11.1-11.2, 11.5-11.7

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
1
of Jordan for the Course: Computer Skills for Engineers (0907101)

Outline

• Introduction
• Pointer Basics
• Arrays and Pointers
• Passing Pointer Arguments in a Function Call
• Returning a Pointer from Functions

2
Introduction

• Pointer variables, simply called pointers, are designed


to hold memory addresses as their values.
• Normally, a variable contains a specific value, e.g., an
integer, a floating-point value, and a character.
• However, a pointer contains the memory address of a
variable that in turn contains a specific value.

Outline

• Introduction
• Pointer Basics
• Arrays and Pointers
• Passing Pointer Arguments in a Function Call
• Returning a Pointer from Functions

4
Pointer Basics

Declare a Pointer
• Like any other variables, pointers must be declared before they
can be used. To declare a pointer, use the following syntax:
dataType* pVarName;

• Each variable being declared as a pointer must be preceded by


an asterisk (*). For example, the following statement declares a
pointer variable named pCount that can point to an int
variable.
int* pCount;
pCount count
Address of Address of variable count Address of variable count 5
pCount

TestPointer Run
6

6
TestPointer.cpp
#include <iostream>
using namespace std;

int main()
{
int count = 5;
int* pCount = &count;

cout << "The value of count is " << count << endl;
cout << "The address of count is " << &count << endl;
cout << "The address of count is " << pCount << endl;
cout << "The value of count is " << *pCount << endl;

return 0; The value of count is 5


} The address of count is 00AFF980
The address of count is 00AFF980
The value of count is 5
7

Dereferencing
• Referencing a value through a pointer is called
indirection. The syntax for referencing a value from a
pointer is:
*pointer

• For example, you can increase count using:


count++; // direct reference
or
(*pCount)++; // indirect reference

• The asterisk (*) is the indirection operator or


dereference operator.
8

8
(a) pY is assigned to pX; (b) *pY is assigned to *pX.

Pointer Type
• A pointer variable is declared with a type such as int,
double, etc.
• You have to assign the address of the variable of the
same type.
• It is a syntax error if the type of the variable does not
match the type of the pointer. For example, the
following code is wrong.

int area = 1;
double* pArea = &area; // Wrong

10

10
Initializing Pointer
• Like a local variable, a local pointer is assigned an
arbitrary value if you don’t initialize it.
• A pointer may be initialized to 0, which is a special
value for a pointer to indicate that the pointer points
to nothing.
• You should always initialize pointers to prevent errors.
• Dereferencing a pointer that is not initialized could
cause fatal runtime error or it could accidentally
modify important data.

11

11

Caution
• You can declare two variables on the same line. For
example, the following line declares two int variables:
int i= 0, j = 1;

• Can you declare two pointer variables on the same line


as follows?
int* pl, pj;

• No, the right way is:


int *pl, *pj;

12

12
Outline

• Introduction
• Pointer Basics
• Arrays and Pointers
• Passing Pointer Arguments in a Function Call
• Returning a Pointer from Functions

13

13

Arrays and Pointers


• An array variable without a bracket and a subscript actually
represents the starting address of the array.
• The array variable is essentially a pointer. Suppose you declare
an array of int value as follows:

int list[6] = { 11, 12, 13, 14, 15, 16 };

14

14
Array Pointer
• *(list + 1) is different from *list + 1. The
dereference operator (*) has precedence over +.
• So, *list + 1 adds 1 to the value of the first
element in the array, while *(list + 1)
dereference the element at address (list + 1)
in the array.

ArrayPointer Run

PointerWithIndex Run

15

15

ArrayPointer.cpp
#include <iostream>
using namespace std;

int main()
{
int list[6] = { 11, 12, 13, 14, 15, 16 };

for (int i = 0; i < 6; i++)


cout << "address: " << (list + i) <<
" value: " << *(list + i) << " " <<
" value: " << list[i] << endl;

return 0;
}

16

16
PointerWithIndex.cpp
#include <iostream>
using namespace std;

int main()
{
int list[6] = { 11, 12, 13, 14, 15, 16 };
int* p = list;

for (int i = 0; i < 6; i++)


cout << "address: " << (list + i) <<
" value: " << *(list + i) << " " <<
" value: " << list[i] << " " <<
" value: " << *(p + i) << " " <<
" value: " << p[i] << endl;

return 0;
}

17

17

Outline

• Introduction
• Pointer Basics
• Arrays and Pointers
• Passing Pointer Arguments in a Function Call
• Returning a Pointer from Functions

18

18
Passing Pointer Arguments
• A pointer argument can be passed by value or by reference. For
example, you can define a function as follows:
void f(int* p1, int*& p2);

• which is equivalently to
typedef int* intPointer;
void f(intPointer p1, intPointer & p2);

• Here p1 is pass-by-value and p2 is pass-by-reference.

TestPointerArgument Run

19

19

TestPointerArgument.cpp 1/5
#include <iostream>
using namespace std;

// Function definitions are here

int main()
{
// Declare and initialize variables
int num1 = 1;
int num2 = 2;

cout << "Before invoking the swap function, num1 is "


<< num1 << " and num2 is " << num2 << endl;

20

20
TestPointerArgument.cpp 2/5
// Swap two variables using pass-by-value
void swap1(int n1, int n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}

// Invoke the swap function to attempt to swap two variables


swap1(num1, num2);
cout << "After invoking the swap function, num1 is “
<< num1 << " and num2 is " << num2 << endl;

21

21

TestPointerArgument.cpp 3/5
// Swap two variables using pass-by-reference
void swap2(int& n1, int& n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}

cout << "Before invoking the swap function, num1 is "


<< num1 << " and num2 is " << num2 << endl;

// Invoke the swap function to attempt to swap two variables


swap2(num1, num2);
cout << "After invoking the swap function, num1 is " << num1
<< " and num2 is " << num2 << endl;

22

22
TestPointerArgument.cpp 4/5
// Pass two pointers by value
void swap3(int* p1, int* p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}

cout << "Before invoking the swap function, num1 is "


<< num1 << " and num2 is " << num2 << endl;
// Invoke the swap function to attempt to swap two variables
swap3(&num1, &num2);
cout << "After invoking the swap function, num1 is " << num1
<< " and num2 is " << num2 << endl;

23

23

TestPointerArgument.cpp 5/5
// Pass two pointers by reference
void swap4(int*& p1, int*& p2)
{
int* temp = p1;
p1 = p2;
p2 = temp;
int* p1 = &num1; }
int* p2 = &num2;
cout << "Before invoking the swap function, p1 is "
<< p1 << " and p2 is " << p2 << endl;
// Invoke the swap function to attempt to swap two variables
swap4(p1, p2);
cout << "After invoking the swap function, p1 is " << p1 <<
" and p2 is " << p2 << endl;

return 0;
}

24

24
Array Parameter or Pointer
Parameter
• An array parameter in a function can always be
replaced using a pointer parameter.

25

25

const Parameter
If an object value does not change, you should declare it
const to prevent it from being modified accidentally.

ConstParameter Run

26

26
ConstParameter.cpp
#include <iostream>
using namespace std;

void printArray(const int*, const int);

int main()
{
int list[6] = { 11, 12, 13, 14, 15, 16 };
printArray(list, 6);

return 0;
}

void printArray(const int* list, const int size)


{
for (int i = 0; i < size; i++)
cout << list[i] << " "; 11 12 13 14 15 16
} 27

27

Outline

• Introduction
• Pointer Basics
• Arrays and Pointers
• Passing Pointer Arguments in a Function Call
• Returning a Pointer from Functions

28

28
Returning a Pointer from Functions
• You can use pointers as parameters in a
function.
• A C++ function may return a pointer as well.

ReverseArrayUsingPointer Run

29

29

ReverseArrayUsingPointer.cpp 1/2
#include <iostream>
using namespace std;

int* reverse(int* list, int size)


{
for (int i = 0, j = size - 1; i < j; i++, j--)
{
// Swap list[i] with list[j]
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}

return list;
}
30

30
ReverseArrayUsingPointer.cpp 2/2
void printArray(const int* list, int size)
{
for (int i = 0; i < size; i++)
cout << list[i] << " ";
}

int main()
{
int list[] = { 1, 2, 3, 4, 5, 6 };
int* p = reverse(list, 6);
printArray(p, 6);

return 0;
}
6 5 4 3 2 1
31

31

Outline

• Introduction
• Pointer Basics
• Arrays and Pointers
• Passing Pointer Arguments in a Function Call
• Returning a Pointer from Functions

32

32

You might also like