Chapter 1: Introduction To Computers, Programs, and C++: Sections 1.1-1.3, 1.6-1.9
Chapter 1: Introduction To Computers, Programs, and C++: Sections 1.1-1.3, 1.6-1.9
Chapter 1: Introduction to
Computers, Programs, and C++
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
1
1/29/20
What is a Computer?
A computer consists of a CPU, memory, hard disk,
monitor, and communication devices.
Bus
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
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
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
Outline
4
1/29/20
Programs
Computer programs, known as software, are instructions
to the computer.
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
12
12
6
1/29/20
13
13
14
14
7
1/29/20
15
15
Outline
16
16
8
1/29/20
17
18
18
9
1/29/20
Comments in C++
19
19
20
20
10
1/29/20
return 0;
} ComputeExpression Run
21
21
Outline
22
22
11
1/29/20
23
23
24
24
12
1/29/20
25
25
Outline
26
26
13
1/29/20
• 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
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
34
34
17
1/29/20
Chapter 2: Elementary
Programming
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
animation
2
1/29/20
animation
animation
3
1/29/20
animation
int main() {
radius 20
double radius; area 1256.636
double area;
animation
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
You can use the cin object to read input from the
keyboard.
ComputeAreaWithConsoleInput Run
10
10
5
1/29/20
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.
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
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.
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.
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
24
24
12
1/29/20
Synonymous Types
25
25
• Floating-point numbers
– 32 bits: float 1.5
– 64 bits: double -1.23456E+2
– 80 bits: long double 9.1e-1000
26
26
13
1/29/20
cout << "1.0 / 3.0 is " << 1.0 / 3.0 << endl;
16 digits
cout << "1.0F / 3.0F is " << 1.0F / 3.0F << endl;
27
27
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.
29
Numeric Literals
int i = 34;
long k = 1000000;
double d = 5.0;
30
30
15
1/29/20
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
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
DisplayTime Run
36
36
18
1/29/20
Exponent Operations
pow(a, b) = ab
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.
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
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:
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
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
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
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:
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
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
57
57
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
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;
61
61
Trace ComputeChange
animation
62
62
31
1/29/20
Trace ComputeChange
animation
63
63
Trace ComputeChange
animation
64
64
32
1/29/20
Trace ComputeChange
animation
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
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
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
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
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.
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
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
16
16
8
1/29/20
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
17
17
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
18
18
9
1/29/20
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
19
19
animation
Trace if-else statement
Suppose score is 70.0 grade is C
20
20
10
1/29/20
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement
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";
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
ComputeBMI Run
31
31
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
34
34
17
1/29/20
35
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
38
38
19
1/29/20
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;
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;
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
TestBooleanOperators Run
45
45
TestBooleanOperators.cpp
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
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
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
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;
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
56
56
28
1/29/20
57
57
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
59
59
animation
60
60
30
1/29/20
animation
61
61
animation
62
62
31
1/29/20
animation
63
63
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
67
67
Examples
• Equivalent statements:
• 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
70
70
35
1/29/20
Operator Precedence
71
71
Operator Associativity
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
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
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
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;
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));
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
13
14
14
7
1/29/20
15
15
Read Characters
To read a character from the keyboard, use
16
16
8
1/29/20
Escape Sequences
C++ uses a special notation to represent special character.
17
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
Display
19
19
ToUppercase Run
20
20
10
1/29/20
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
23
23
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
GuessBirthday Run
26
26
13
1/29/20
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
CharacterFunctions Run
30
30
15
1/29/20
Character Functions
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
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
36
36
18
1/29/20
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:
40
40
20
1/29/20
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);
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
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
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
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
displays
□□□□1.23
□□351.34
51
51
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
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
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
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:
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 …
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
int count = 0;
while (count < 100)
{
cout << "Welcome to C++!\n";
count++;
}
3
1/29/20
animation
4
1/29/20
animation
animation
10
10
5
1/29/20
animation
11
11
animation
12
12
6
1/29/20
animation
13
13
animation
14
14
7
1/29/20
animation
15
15
animation
16
16
8
1/29/20
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;
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
20
20
10
1/29/20
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;
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
25
25
SentinelValue Run
26
26
13
1/29/20
SentinelValue.cpp
int data;
cin >> data;
27
28
28
14
1/29/20
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
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;
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
36
18
1/29/20
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
37
37
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
38
38
19
1/29/20
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
39
39
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
40
40
20
1/29/20
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
41
41
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
42
42
21
1/29/20
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
43
43
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
44
44
22
1/29/20
animation
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
45
45
animation
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.
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
• The for loop can generally be converted into the while loop.
50
50
25
1/29/20
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.
MultiplicationTable Run
53
53
MultiplicationTable.cpp 1/2
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << " Multiplication Table\n";
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
}
57
57
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
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
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
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
13
13
animation
14
14
7
1/29/20
animation
15
15
animation
16
16
8
1/29/20
animation
17
17
animation
18
18
9
1/29/20
animation
19
19
animation
20
20
10
1/29/20
animation
21
21
animation
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.
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';
} }
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);
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
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
return 0;
}
32
32
16
1/29/20
PrimeNumberFunction.cpp 1/3
#include <iostream>
#include <iomanip>
using namespace std;
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
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;
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;
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;
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.
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.
InlineExpandedDemo
50
50
25
1/29/20
InlineDemo.cpp
#include <iostream>
using namespace std;
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
54
54
27
1/29/20
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(); }
57
57
58
29
1/29/20
StaticVariableDemo Run
59
59
StaticVariableDemo.cpp
#include <iostream>
using namespace std;
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 n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;
67
SwapByReference.cpp 2/2
int main()
{
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
cout << "After invoking the swap function, num1 is " << num1
<< " and num2 is " << num2 << endl;
return 0;
}
68
68
34
1/29/20
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
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
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;
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
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
6
Arbitrary Initial Values
arrayName[index];
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
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
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:
28
28
Copying Arrays
Can you copy array using a syntax like this?
list = myList; // Does not work
29
29
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
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
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
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:
// Initialize cards
for (int i = 0; i < NUMBER_OF_CARDS; i++)
deck[i] = i;
39
39
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;
}
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
PassArrayDemo Run
44
44
PassArrayDemo.cpp
#include <iostream>
using namespace std;
int main()
{
int numbers[6] = { 1, 4, 3, 6, 8, 9 };
printArray(numbers, 6); // Invoke the function
return 0;
}
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;
int main()
{
int x = 1; // x represents an int value
int y[10] = { 0 }; // y represents an array of int values
return 0;
}
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.
49
ConstArrayDemo.cpp
#include <iostream>
using namespace std;
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
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;
54
ReverseArray.cpp 1/2
int main()
{
const int SIZE = 6;
int list[] = { 1, 2, 3, 4, 5, 6 };
int newList[SIZE];
return 0;
} 55
55
animation
1 2 3 4 5 6
list
newList 0 0 0 0 0 0
56
56
animation
1 2 3 4 5 6
list
newList 0 0 0 0 0 0
57
57
animation
1 2 3 4 5 6
list
newList 0 0 0 0 0 0
58
58
animation
1 2 3 4 5 6
list
newList 0 0 0 0 0 1
59
59
animation
1 2 3 4 5 6
list
newList 0 0 0 0 0 1
60
60
animation
1 2 3 4 5 6
list
newList 0 0 0 0 0 1
61
61
animation
1 2 3 4 5 6
list
newList 0 0 0 0 2 1
62
62
animation
1 2 3 4 5 6
list
newList 0 0 0 0 2 1
63
63
animation
1 2 3 4 5 6
list
newList 0 0 0 0 2 1
64
64
animation
1 2 3 4 5 6
list
newList 0 0 0 3 2 1
65
65
animation
1 2 3 4 5 6
list
newList 0 0 0 3 2 1
66
66
animation
1 2 3 4 5 6
list
newList 0 0 0 3 2 1
67
67
animation
1 2 3 4 5 6
list
newList 0 0 4 3 2 1
68
68
animation
1 2 3 4 5 6
list
newList 0 0 4 3 2 1
69
69
animation
1 2 3 4 5 6
list
newList 0 0 4 3 2 1
70
70
animation
1 2 3 4 5 6
list
newList 0 5 4 3 2 1
71
71
animation
1 2 3 4 5 6
list
newList 0 5 4 3 2 1
72
72
animation
1 2 3 4 5 6
list
newList 0 5 4 3 2 1
73
73
animation
1 2 3 4 5 6
list
newList 6 5 4 3 2 1
74
74
animation
1 2 3 4 5 6
list
newList 6 5 4 3 2 1
75
75
animation
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:
81
81
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
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";
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
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
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];
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
8
Printing Arrays
• To print a two-dimensional array, you have to print each
element in the array using a loop like the following:
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:
11
11
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
PassTwoDimensionalArray Run
14
14
PassTwoDimensionalArray.cpp 1/2
#include <iostream>
using namespace std;
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];
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
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;
19
GradeExam.cpp 2/2
// Key to the questions
char keys[] = { 'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D' };
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.
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.
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];
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
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];
}
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
Sections 17.1-17.2
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;
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
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)
17
17
animation
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)
18
18
9
1/29/20
animation
19
19
animation
20
20
10
1/29/20
animation
21
21
animation
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)
22
22
11
1/29/20
animation
23
23
animation
24
24
12
1/29/20
animation
25
25
animation
26
26
13
1/29/20
animation
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)
27
27
28
28
14
1/29/20
Outline
• Introduction
• Example: Factorials
29
29
15
Chapter 9: Objects and Classes
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
6
Example of the class for Circle objects
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
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);
13
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 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();
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);
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.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
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;
29
29
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.
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;
34
Circle.cpp
#include "Circle.h"
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);
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
38
Accessor and Mutator
• A get function is referred to as a getter (or accessor).
• A get function has the following signature:
returnType getPropertyName()
39
39
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;
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
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
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;
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;
Dereferencing
• Referencing a value through a pointer is called
indirection. The syntax for referencing a value from a
pointer is:
*pointer
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;
12
12
Outline
• Introduction
• Pointer Basics
• Arrays and Pointers
• Passing Pointer Arguments in a Function Call
• Returning a Pointer from Functions
13
13
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 };
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;
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);
TestPointerArgument Run
19
19
TestPointerArgument.cpp 1/5
#include <iostream>
using namespace std;
int main()
{
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
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;
}
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;
}
22
22
TestPointerArgument.cpp 4/5
// Pass two pointers by value
void swap3(int* p1, int* p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
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;
int main()
{
int list[6] = { 11, 12, 13, 14, 15, 16 };
printArray(list, 6);
return 0;
}
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;
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