Beruflich Dokumente
Kultur Dokumente
Input devices
Allows people to supply information to computers
Output devices
Allows people to receive information from computers
Computer Organization
Memory
Input Output
Devices Devices
CPU
CPU
Brains of the computer
Arithmetic calculations are performed using the
Store information
resolution of 1280 by
1024 or better
Number of colors supported varies from 16 to billions
Software
Application software
Programs designed to perform specific tasks that are
System software
Programs that support the execution and
Operating systems
Translation systems
Application Software
Application software is the software that has made
using computers indispensable and popular
Spreadsheets
Presentation managers
Drawing programs
system
Sort, delete, copy
Ability to perform input and output on a variety of
devices
Translation System
Set of programs used to develop software
Combines resources
Examples
Microsoft Visual C++®, CBuilder®, g++, Code
Warrior®
Performs compilation, linking, and other activities.
Software Development
Activities
Editing
Compiling
Library modules
Source Program
Compile
Library routines
Edit Link
Other object files
Think Load
Execute
IDEs
Integrated Development Environments or IDEs
Supports the entire software development cycle
Compiler
Linker
Loader
Debugger
Viewer
Engineering Software
Software engineering
Area of computer science concerned with building
Challenge
Tremendous advances in hardware have not been
High
Total Software
Complexity
Complexity
User Simplicity
Low
Software Engineering Goals
Reliability
An unreliable life-critical system can be fatal
Understandability
Future development is difficult if software is hard to
understand
Cost Effectiveness
Cost Effectiveness
Cost to develop and maintain should not exceed profit
Adaptability
Adaptability
System that is adaptive is easier to alter and expand
Reusability
Reusability
Improves reliability, maintainability, and profitability
Software Engineering
Principles
Abstraction
Extract the relevant properties while ignoring
inessentials
Encapsulation
Encapsulation
Hide and protect essential information through a
controlled interface
Modularity
Modularity
Dividing an object into smaller modules so that it is
Example - car
Car dealer views a car from selling features
standpoint
Price, length of warranty, color, …
Ignition system
Battery Starter Spark plugs
Hierarchy
Hierarchy
Ranking or ordering of objects based on some
properties
Weight, size, can send message
to the television
The television is also a physical object
01011 = 0 • 24 + 1 • 23 + 0 • 22 + 1 • 21 + 1 • 20
= 11
00010 = 0 • 24 + 0 • 23 + 0 • 22 + 1 • 21 + 0 • 20
= 2
00010 2 Equivalent
Binary
+ 01011 + 11 decimal
addition
01101 13 addition
Binary Arithmetic
Binary Equivalent decimal
multiplication multiplication
0101 5
× 0011 × 3
0101 15
0101
0000
0000
0001111
Two’s Complement
Representation for signed binary numbers
Replace all the 1's with 0's, and all the 0's with 1's
8 - 7 = 8 + (-7) = 1
Declaration
Action
Executable unit
Named set of program statements
different names
Subroutine: Fortran and Basic
Procedure: Pascal
Function : C++
Program Organization
C++ program
Collection of definitions, declarations and functions
Advantages
Structured into small understandable units
Complexity is reduced
Values or properties
Data members
Ability to react to requests (messages)!!
Member functions
When an object receives a message, one of two actions
are performed
Object is directed to perform an action
cout << "Area = " << Area << " = Length "
<< Length << " * Width " << Width << endl;
return 0;
}
Visual C++ IDE with
Area.cpp
Area.cpp Output
Comments
Allow prose or commentary to be included in program
Importance
Programs are read far more often than they are
written
Programs need to be understood so that they can be
maintained
C++ has two conventions for comments
// single line comment (preferred)
Typical uses
Identify program and who wrote it
Floating-point objects Z
5 1.28345
Character objects
1 3.14
P
Integer Object Types
The basic integer object type is int
The size of an int depends on the machine and the
compiler
On PCs it is normally 16 or 32 bits
Other integers object types
short: typically uses less bits
Octal (base 8)
Digits 0, 1, 2, 3, 4, 5, 6, 7
Hexadecimal (base 16)
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a , b, c, d, e, f, A,
B, C, D, E, F
Consider
31 oct and 25 dec
Decimal Constants
Examples
97
L or l indicates long
40000L
integer
50000
23a (illegal)
Fractional part
double
long double
Floating-Point Constants
Standard decimal notation
134.123 F or f indicates single
0.15F precision floating point
value
Standard scientific notation
1.45E6 L or l indicates long double
0.979e-3L floating point value
Digits
Identifiers
Keywords
Keywords are words reserved as part of the language
int, return, float, double
Temperature
CameraAngle
CurrentNbrPoints
Definitions
All objects that are used in a program must be defined
Name
Examples
3 / 2 evaluates to 1
4 / 6 evaluates to 0
10 / 3 evaluates to 3
Mod
Produces the remainder of the division
Examples
5 % 2 evaluates to 1
12 % 4 evaluates to 0
4 % 5 evaluates to 4
Operators and Precedence
Consider mx + b
Consider m*x + b which of the following is it equivalent
to
(m * x) + b
m * (x + b)
Operator precedence tells how to evaluate expressions
Standard precedence order
() Evaluate first, if nested innermost
done first
*/% Evaluate second. If there are
several,
then evaluate from left-to-right
+- Evaluate third. If there are several,
then evaluate from left-to-right
Operator Precedence
Examples
20 - 4 / 5 * 2 + 3 * 5 % 4
(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
Defining and Initializing
When an object is defined using the basic form, the
memory allotted to it contains random information
Action
Expression is evaluated
OldStudents = TotalStudents;
Assignment Statement
int NewStudents = 6; NewStudents 6
int OldStudents = 21; OldStudents 27
int TotalStudents; TotalStudents 27
OldStudents = TotalStudents;
Consider
int Value1 = 10; Value1 10
Consider
int Value1 = 10; Value1 10
int Value2 = 20; Value2 20
Consider
int Value1 = 10; Value1 10
int Value2 = 20; Value2 20
int Hold = Value1; Hold 10
Consider
int Value1 = 10; Value1 ?
int Value2 = 20; Value2 20
int Hold = Value1; Hold 10
Value1 = Value2;
Consider
int Value1 = 10; Value1 20
int Value2 = 20; Value2 20
int Hold = Value1; Hold 10
Value1 = Value2;
Consider
int Value1 = 10; Value1 20
int Value2 = 20; Value2 ?
int Hold = Value1; Hold 10
Value1 = Value2;
Value2 = Hold;
Consider
int Value1 = 10; Value1 20
int Value2 = 20; Value2 10
int Hold = Value1; Hold 10
Value1 = Value2;
Value2 = Hold;
i = i + 1; i 2
Evaluates to 2
Const Definitions
Modifier const indicates that an object cannot be
changed
Object is read-only
Consider
float y = 2.7;
int i = 15;
int j = 10;
i = y; // i is now 2
cout << i << endl;
y = j; // y is now 10.0
cout << y << endl;
Nonfundamental Types
Nonfundamental as they are additions to the language
C++ permits definition of new types and classes
A class is a special kind of type
Class objects typically have
Data members that represent attributes and values
Member functions for object inspection and
manipulation
Members are accessed using the selection operator
(.)
j = s.size();
Auxiliary functions for other behaviors
Libraries often provide special-purpose types and
classes
Examples
Standard Template Library (STL) provides class string
single object
Some definitions
string Name = "Joanne";
string DecimalPoint = ".";
string empty = "";
string copy = name;
string Question = '?'; // illegal
Nonfundamental Types
To access a library use a preprocessor directive to add
its definitions to your program file
#include <string>
The using statement makes syntax less clumsy
Without it
std::string s = "Sharp";
std::string t = "Spiffy";
With it
return 0;
}
An EzWindows Project File
An EzWindows Project File
Sample Display Behavior
RectangleShape Objects
EzWindows also provides RectangleShape for manipulating
rectangles
RectangleShape objects can specify the following attributes
SimpleWindow object that contains the rectangle
(mandatory)
Offset from left edge of the SimpleWindow
Offset from top edge of the SimpleWindow
Offsets are measured in centimeters from rectangle
center
Width in centimeters
Height in centimeters
Color
RectangleShape Objects
Examples
SimpleWindow W1("My Window", 20, 20);
SimpleWindow W2("My Other Window", 15, 10);
Examples
int i = 3;
i += 4; // i is now 7
cout << i << endl;
float a = 3.2;
a *= 2.0; // a is now 6.4
cout << a << endl;
Increment and Decrement
C++ has special operators for incrementing or
decrementing an object by one
Examples
int k = 4;
++k; // k is 5
k++; // k is 6
cout << k << endl;
int i = k++; // i is 6, k is 7
cout << i << " " << k << endl;
int j = ++k; // j is 8, k is 8
cout << j << " " << k << endl;
Class string
Some string member functions
size() determines number of characters in the string
string Saying = "Rambling with Gambling";
cout << Saying.size() << endl; // 22
substr() determines a substring (Note first position has
index 0)
string Word = Saying.substr(9, 4); // with
find() computes the position of a subsequence
int j = Saying.find("it"); // 10
int k = Saying.find("its"); // ?
Class string
Auxiliary functions and operators
getline() extracts the next input line
string Response;
cout << "Enter text: ";
getline(cin, Response, '\n');
cout << "Response is \"" << Response
<< "\"” << endl;
Example run
Enter text: Want what you do
Response is "Want what you do"
Class string
Auxiliary operators
+ string concatenation
string Part1 = "Me";
string Part2 = " and ";
string Part3 = "You";
string All = Part1 + Part2 + Part3;
+= compound concatenation assignment
string ThePlace = "Brooklyn";
ThePlace += ", NY";
#include <iostream>
using namespace std;
int main() {
cout << "Enter the date in American format: "
<< "(e.g., January 1, 2001) : ";
string Date;
getline(cin, Date, '\n');
int i = Date.find(" ");
string Month = Date.substr(0, i);
int k = Date.find(",");
string Day = Date.substr(i + 1, k - i - 1);
string Year = Date.substr(k + 2, Date.size() - 1);
string NewDate = Day + " " + Month + " " + Year;
cout << "Original date: " << Date << endl;
cout << "Converted date: " << NewDate << endl;
return 0;
}
If Control Construct
A mechanism for deciding
whether an action should be
taken
Or
Not
Boolean Algebra
Truth tables
Lists all combinations of operand values and the
Example
P Q P and Q
P Q P or Q
P not P
False True
True False
Boolean Algebra
Can create complex logical expressions by combining
simple logical expressions
Example
not (P and Q)
false
Boolean operators
The and operator is &&
The or operator is ||
Warning
& and | are also operators so be careful what you
type
A Boolean Type
Example logical expressions
bool P = true;
bool Q = false;
bool R = true;
bool S = (P && Q);
bool T = ((!Q) || R);
bool U = !(R && (!Q));
Relational Operators
Equality operators
==
!=
Examples
int i = 32;
int k = 45;
bool q = (i == k);
bool r = (i != k);
Relational Operators
Ordering operators
<
>
>=
<=
Examples
int i = 5;
int k = 12;
executed
Two constructs
If statement
if
if-else
if-else-ef
Switch statement
Left for reading
The Basic If Statement
Syntax
if (Expression)
Action
Expression
If the Expression is true then
execute Action
true false
Our number is
now definitely
nonnegative
Sorting Two Numbers
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
if (Value1 > Value2) {
int RememberValue1 = Value1;
Value1 = Value2;
Value2 = RememberValue1;
}
cout << "The input in sorted order: "
<< Value1 << " " << Value2 << endl;
Semantics Are the numbers
out of order
Rearrange value1
and value2 to value2 < value1
put their values
in the proper
order true false
if (m < n)
++m;
++n;
cout << " m = " << m << " n = " n << endl;
The If-Else Statement
Syntax
if (Expression)
Action1
else
Action2 Expression
If Expression is true then execute
Action1 otherwise execute Action2 true false
if (v == 0) {
cout << "v is 0"; Action1 Action2
}
else {
cout << "v is not 0";
}
Finding the Max
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
int Max;
if (Value1 < Value2) {
Max = Value2;
}
else {
Max = Value1;
}
cout << "Maximum of inputs is: " << Max << endl;
Finding the Max Is Value2 larger than Value1
Yes, it is . So Value2 is
larger than Value1. In
this case, Max is set No, its not. So Valu
to Value2 is at least as large a
Value2. In this case
Value1 < Value2 Max is set to Value
true false
Switch statement
An advanced construct
An If-Else-If Statement
if ( nbr < 0 ){
cout << nbr << " is negative" << endl;
}
else if ( nbr > 0 ) {
cout << nbr << " is positive" << endl;
}
else {
cout << nbr << " is zero" << endl;
}
A Switch Statement
switch (ch) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
cout << ch << " is a vowel" << endl;
break;
default:
cout << ch << " is not a vowel" << endl;
}
cout << "Enter simple expression: ";
int Left;
int Right;
char Operator;
cin >> Left >> Operator >> Right;
cout << Left << " " << Operator << " " << Right
<< " = ";
switch (Operator) {
case '+' : cout << Left + Right << endl; break;
case '-' : cout << Left - Right << endl; break;
case '*' : cout << Left * Right << endl; break;
case '/' : cout << Left / Right << endl; break;
default: cout << "Illegal operation" << endl;
}
Iterative Constructs
Mechanisms for deciding under
what conditions an action should
be repeated
for statement
do-while statement
While Syntax
Expression
If Expression is
true, Action is true false
executed If Expression is
false, program
Action execution
continues with
next statement
Computing an Average
int listSize = 4;
int numberProcessed = 0;
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
int listSize = 4;
int numberProcessed = 0;
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 0
int listSize = 4;
int numberProcessed = 0;
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 0
int listSize = 4; sum 0
int numberProcessed = 0;
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 0
int listSize = 4; sum 0
int numberProcessed = 0;
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 0
int listSize = 4; sum 0
int numberProcessed = 0; value --
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 0
int listSize = 4; sum 0
int numberProcessed = 0; value 1
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 0
int listSize = 4; sum 0
1
int numberProcessed = 0; value 1
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 0
1
int listSize = 4; sum 1
int numberProcessed = 0; value 1
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 1
int listSize = 4; sum 1
int numberProcessed = 0; value 1
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 1
int listSize = 4; sum 1
int numberProcessed = 0; value --
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 1
int listSize = 4; sum 1
int numberProcessed = 0; value 5
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 1
int listSize = 4; sum 1
6
int numberProcessed = 0; value 5
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 1
2
int listSize = 4; sum 6
int numberProcessed = 0; value 5
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 2
int listSize = 4; sum 6
int numberProcessed = 0; value 5
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 2
int listSize = 4; sum 6
int numberProcessed = 0; value --
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 2
int listSize = 4; sum 6
int numberProcessed = 0; value 3
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 2
int listSize = 4; sum 6
9
int numberProcessed = 0; value 3
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 2
3
int listSize = 4; sum 9
int numberProcessed = 0; value 3
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 3
int listSize = 4; sum 9
int numberProcessed = 0; value 3
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 3
int listSize = 4; sum 9
int numberProcessed = 0; value --
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 3
int listSize = 4; sum 9
int numberProcessed = 0; value 1
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 3
int listSize = 4; sum 10
9
int numberProcessed = 0; value 1
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 3
4
int listSize = 4; sum 10
int numberProcessed = 0; value 1
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 3
4
int listSize = 4; sum 10
int numberProcessed = 0; value 1
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 3
4
int listSize = 4; sum 10
int numberProcessed = 0; average 2.5
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace listSize 4
numberProcessed 3
4
int listSize = 4; sum 10
int numberProcessed = 0; average 2.5
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Suppose input contains: 1 5 3 1
6
Execution Trace
Stays in stream until
int listSize = 4; extracted
int numberProcessed = 0;
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
++numberProcessed;
}
double average = sum / numberProcessed ;
cout << "Average: " << average << endl;
Power of Two Table
const int TableSize = 20;
int i = 0;
long Entry = 1;
cout << "i" << "\t\t" << "2 ** i" << endl;
Example
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
Evaluated once
at the beginning
of the for
statements's ForInit
The ForExpr is
execution evaluated at the
start of each
iteration of the
loop
If ForExpr is ForExpr
true, Action is
executed true false
PostExpr
i is 0
Execution Trace
i 0
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
Execution Trace
i 1
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
Execution Trace
i 1
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
Execution Trace
i 1
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
Execution Trace
i 1
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
Execution Trace
i 2
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
Execution Trace
i 2
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
Execution Trace
i 2
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
i is 2
Execution Trace
i 2
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
i is 2
Execution Trace
i 3
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
i is 2
Execution Trace
i 3
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
i is 2
Execution Trace
i 3
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i is 1
i is 2
all done
Table Revisiting
const int TableSize = 20;
long Entry = 1;
long Entry = 1;
++Counter1;
for (int i = 1; i <= 10; ++i) {
++Counter2;
{
ForInit;
while (ForExpression) {
Action;
PostExpression;
}
}
Counting Characters
int NumberOfNonBlanks = 0;
int NumberOfUpperCase = 0;
char c; Only extracts
while (cin >> c) { nonblank characters
++NumberOfNonBlanks;
if ((c >= 'A') && (c <= 'Z')) {
++NumberOfUpperCase;
}
}
cout << "Nonblank characters: " << NumberOfNonBlanks
<< endl << "Uppercase characters: "
<< NumberOfUpperCase << endl;
Counting All Characters
char c;
int NumberOfCharacters = 0;
int NumberOfLines = 0;
Extracts all
while ( cin.get(c) ) { characters
++NumberOfCharacters;
if (c == '\n') {
++NumberOfLines
}
}
cout << "Characters: " << NumberOfCharacters
<< endl << "Lines: " << NumberOfLines
<< endl;
#include <iostream>
#include <fstream>
using namespace std;
File Processing
int main() {
ifstream fin("mydata.txt");
int ValuesProcessed = 0;
float ValueSum = 0;
float Value;
while ( fin >> Value ) {
ValueSum += Value;
++ValuesProcessed;
}
if (ValuesProcessed > 0) {
ofstream fout("average.txt");
float Average = ValueSum / ValuesProcessed;
fout << "Average: " << Average << endl;
return 0;
}
else {
cerr << "No list to average" << endl;
return 1;
}
}
Iteration Do’s
Key Points
Make sure there is a statement that will eventually
If Expression is true
there
Terminology
A function is invoked by a function call / function
invocation
y = f(a);
Terminology
A function call specifies
The function name
y = f(a);
y = f(a);
Terminology
A function call produces a return value
The return value is the value of the function call
y = f(a);
Invocation Process
Flow of control is temporarily transferred to the invoked
function
Correspondence established between actual
invoked function
by commonality of purpose
Include statement provides access to the names and
Previous examples
String: STL’s string class
Graphics: EzWindows
Basic Translation Process
Source program
Executable Unit
Some Standard Libraries
fstream
File stream processing
assert
C-based library for assertion processing
iomanip
Formatted input/output (I/O) requests
ctype
C-based library for character manipulations
math
C-based library for trigonometric and logarithmic
functions
Note
Library Header Files
Describes library components
Typically contains
Function prototypes
Interface description
Class definitions
Sometimes contains
Object definitions
by a linker
#include <iostream>
#include <cmath> Library header files
using namespace std;
int main() {
cout << "Enter Quadratic coefficients: ";
double a, b, c;
cin >> a >> b >> c; Invocation
if ( (a != 0) && (b*b - 4*a*c > 0) ) {
double radical = sqrt(b*b - 4*a*c);
double root1 = (-b + radical) / (2*a);
double root2 = (-b - radical) / (2*a);
cout << "Roots: " << root1 << " " << root2;
}
else {
cout << "Does not have two real roots";
}
return 0;
}
#include <iostream>
#include <fstream> // file stream library
using namespace std;
int main() {
ifstream fin("mydata.txt");
int ValuesProcessed = 0;
float ValueSum = 0;
float Value;
while (fin >> Value) {
ValueSum += Value;
++ValuesProcessed;
}
if (ValuesProcessed > 0) {
ofstream fout("average.txt");
float Average = ValueSum / ValuesProcessed;
fout << "Average: " << Average << endl;
return 0;
}
else {
cerr << "No list to average" << endl;
return 1;
}
}
ifstream sin("in1.txt"); // extract from in1.txt
ofstream sout("out1.txt"); // insert to out1.txt
string s;
while (sin >> s) {
sout << s << endl;
}
sin.close(); // done with in1.txt
sout.close(); // done with out1.txt
sin.open("in2.txt"); // now extract from in2.txt
sout.open("out.txt", // now append to out2.txt
(ios_base::out | ios_base::app));
while (sin >> s) {
sout << s << endl;
}
sin.close(); // done with in2.txt
sout.close(); // done with out2.txt
Programmer-defined
Functions
Development of simple
functions using value and
reference parameters
Actual parameter
Using statements
Function prototypes
Function definitions
Parameters
Return
value
Information from
function can come
through a return
value or an output
stream
PromptAndRead()
// PromptAndRead(): prompt and extract next
// integer
int PromptAndRead() {
cout << "Enter number (integer): ";
int Response;
cin >> Response;
return Response;
}
Sum()
// Sum(): compute sum of integers in a ... b
int Sum(int a, int b) {
int Total = 0;
for (int i = a; i <= b; ++i) {
Total += i;
}
return Total;
}
Problem
Definition
Input two numbers that represent a range of integers
Design
Prompt user and read the first number
parameter
That would work!
Reference Parameters
If the formal argument declaration is a reference
parameter then
Formal parameter becomes an alias for the actual
parameter
Changes to the formal parameter change the
actual parameter
Function definition determines whether a parameter’s
passing style is by value or by reference
Reference parameter form
ptypei &pnamei
Why is MyNumber a
reference parameter? Why is the stream a
reference parameter?
Getnum.cpp
int main() {
ifstream fin("mydata.txt");
int Number1;
int Number2;
cout << "Enter number: ";
GetNumber(Number1, cin);
// not needed: cout << "Enter number: ";
GetNumber(Number2, fin);
if (Number1 > Number2) {
Swap(Number1, Number2);
}
cout << "The numbers in sorted order: "
<< Number1 << ", " << Number2 << endl;
return 0;
}
Constant Parameters
The const modifier can be applied to formal parameter
declarations
const indicates that the function may not modify the
parameter
void PromptAndGet(int &n, const string &s) {
cout << s ;
cin >> n ;
// s = "Got it"; // illegal assignment
} // caught by compiler
Sample invocation
int x;
PromptAndGet(x, "Enter number (n): ");
Constant Parameters
Usefulness
When we want to pass an object by reference, but
Question
Why not just pass the object by value?
Answer
For
? large objects, making a copy of the object can be
very inefficient
Passing Constant Rectangles
void DrawBoxes(const RectangleShape &R1,
const RectangleShape &R2) {
R1.Draw();
R2.Draw();
}
int ApiMain() {
SimpleWindow Demo("Demo Program");
Demo.Open();
RectangleShape Rect1(Demo, 3, 2, Blue);
RectangleShape Rect2(Demo, 6, 5, Yellow);
DrawBoxes(Rect1, Rect2);
return 0;
}
Default Parameters
Observations
Our functions up to this point required that we
Default parameters
Allows programmer to define a default behavior
then
If there is no ith argument in the function invocation,
pnamei is initialized to dvaluei
The parameter pnamei is an optional value
parameter
PrintChar('*', 20);
PrintChar('-');
PrintChar();
Default Parameters
Default parameters must appear after any mandatory
parameters
Bad example
void Trouble(int x = 5, double z, double y) {
...
}
interfaces
Typically this means different formal parameter
lists
Difference in number of parameters
Min(a, b, c)
Min(a, b)
Difference in types of parameters
Min(10, 20)
Min(4.4, 9.2)
Function Overloading
int Min(int a, int b) {
cout << "Using int min()" << endl;
if (a > b)
return b;
else
return a;
}
double Min(double a, double b) {
cout << "Using double min()" << endl;
if (a > b)
return b;
else
return a;
}
Function Overloading
int main() {
int a = 10;
int b = 20;
double x = 4.4;
double y = 9.2;
int c = Min(a, b);
cout << "c is " << c << endl;
int z = Min(x, y);
cout << "z is " << z << endl;
return 0;
}
Function Overloading
Compiler uses function overload resolution to call the
most appropriate function
First looks for a function definition where the formal
Consider seed.cpp
int main() {
cout << "Enter a seed: ";
unsigned int Seed;
cin >> Seed;
srand(Seed);
for (int i = 1; i <= 5; ++i)
cout << rand() << endl;
return 0;
}
Different Sequences
To automatically get a different sequence each time
Need a method of setting the seed to a random
value
The standard method is to use the computer's
clock as the value of the seed
The function invocation time() can be used
Returns an integral value of type time_t
Invocation time(0) returns a suitable value
for generating a random sequence
Randseed.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand((unsigned int) time(0));
for (int i = 1; i <= 5; ++i)
cout << rand() << endl;
return 0;
}
Class Construct
Defining objects with
attributes and behavior
representing information
Object behaviors
Realized in C++ via member functions (methods)
Object attributes
Are known as data members in C++
SetSize()
SetColor()
Draw()
Member Functions
Constructors
Member functions that initialize an object during its
definition
RectangleShape R(W, x, y, c, w, h);
Factoid
Constructors do not have a type
Considered superfluous
Member Functions
Inspectors
Member functions that act as a messenger that
Example
RectangleShapes have an inspector GetColor()
Example
RectangleShapes have a mutator SetColor()
R.SetColor(Black);
Member Functions
Facilitators
Causes an object to perform some action or service
Example
RectangleShapes have a facilitator Draw()
R.Draw();
A Simple RectangleShape
Class
Consider a simpler version of the RectangleShape than
what is defined in rect.h
// mutators
void SetColor(const color &c);
void SetPosition(float XCoord, float YCoord);
void SetSize(float Width, float Height);
Simple RectangleShape
Access right
private:
// data members A client cannot
SimpleWindow &Window; directly access either
private or protected
float thisXCenter; data members
float thisYCenter;
color thisColor;
float thisWidth;
float thisHeight;
};
#endif
Close of #ifndef directive
Access Tests
Consider
SimpleWindow W("Testing", 20, 10);
RectangleShape R(W, 2, 2, Blue, 4, 3);
const RectangleShape S(W, 15, 10, Red, 5, 6);
color d = S.GetColor();
color d = R.thisColor;
R.DetColor(Yellow);
S.SetColor(Black);
The RectangleShape Class
Public access
All clients and class members
Instantiations
O: R1 O: R2
DM: Window: &W, DM: Window: &W,
Color: Cyan, Color: Red,
XCenter: 1, YCenter: 4 XCenter: 6, YCenter: 4
Width: 3, Height: 3 Width: 1, Height: 2
#include "rect.h”
SimpleWindow ColorWindow("Color Palette", 8.0, 8.0);
int ApiMain() {
const int SideSize = 1;
float XPosition = 1.5;
const float YPosition = 4;
ColorWindow.Open();
RectangleShape ColorPatch(ColorWindow,
XPosition, YPosition, White, SideSize, SideSize);
for (int c = Red; c <= Magenta; c = color(c + 1)) {
ColorPatch.SetColor(color(c));
ColorPatch.SetPosition(XPosition, YPosition);
ColorPatch.Draw();
XPosition += SideSize;
}
return 0;
}
Abstract Data Types
Development and
Implementation
Example
programming a microwave to make popcorn should
Standard operations
Addition Multiplication
a c ad+bc a c ac
+ = * =
b d bd b d bd
Subtraction Division
a c ad - bc a c ad
- = / =
b d bd b d bc
Abstract Data Type
Consider
Rational a(1,2); // a = 1/2
Rational b(2,3); // b = 2/3
cout << a << " + " << b << " = " << a + b;
Rational s; // s = 0/1
Rational t; // t = 0/1
cin >> s >> t;
cout << s << " * " << t << " = " << s * t;
Observation
Natural look that is analogous to fundamental-type
arithmetic objects
Rational Attributes
A numerator and denominator
Implies in part a class representation with two
Rational relational
Equality and less than comparisons
Provided automatically
Assignment
Provided automatically
operations
Provides the natural form we expect
Class definition provides a functional form that
Instantiation Instantiation
Rational a(1,2); Rational b(2,3);
Object a Object b
Attributes: Attributes:
NumeratorValue(1) NumeratorValue(2)
DenominatorValue(2) DenominatorValue(3)
Library Components
Rational.h
Class definitions and library function prototypes
Rational.cpp
Implementation source code – member and auxiliary
function definitions
Auxiliary functions are assisting global functions
that provide expected but non-member
capabilities
Rational.obj
Translated version of Rational.cpp (linkable)
Rational.lib
Library version of Rational.obj that is more readily
linkable
MyProgram.cpp
Making use of the Rational
class. The header file provides
#include <iostream> access to the class definition
using namespace std; and to auxiliary function
#include "rational.h" prototypes. The header file
int main() { does not provide member and
auxiliary definitions
Rational r;
Rational s;
cout << "Enter two rationals(a/b): ";
cin >> r >> s;
Rational Sum = r + s;
cout << r << " + " << s << " = " << Sum;
return 0;
}
Producing MyProgram.exe
Preprocessor combines the definitions and prototypes in
iostream and rational headers along with
MyProgram.cpp to produce a compilation unit
Compiler must be told where to look for Rational.h
MyProgram.exe
Rational Header File
Overview
File layout
Class definition and library prototypes nested within
preprocessor statements
Ensures one inclusion per translation unit
Class definition precedes library prototypes
#ifndef RATIONAL_H
#define RATIONAL_H
class Rational {
// …
} ;
// library prototypes …
#endif
Class Rational Overview
class Rational { // from rational.h
public:
// for everybody including clients
protected:
// for Rational member functions and for
// member functions from classes derived
// from rational
private:
// for Rational member functions
} ;
Rational Public Section
public:
// default constructor
Rational();
// specific constructor
Rational(int numer, int denom = 1);
// arithmetic facilitators
Rational Add(const Rational &r) const;
Rational Multiply(const Rational &r) const;
// stream facilitators
void Insert(ostream &sout) const;
void Extract(istream &sin);
Rational Protected Section
protected:
// inspectors
int GetNumerator() const;
int GetDenominator() const;
// mutators
void SetNumerator(int numer);
void SetDenominator(int denom);
Rational Private Section
private:
// data members
int NumeratorValue;
int DenominatorValue;
Auxiliary Operator
Prototypes
// after the class definition in rational.h
Rational operator+(
const Rational &r, const Rational &s);
Rational operator*(
const Rational &r, const Rational &s);
ostream& operator<<(
ostream &sout, const Rational &s);
r << cout;
Const Power
const Rational OneHalf(1,2);
cout << OneHalf; // legal
cin >> OneHalf; // illegal
Rational Implementation
#include <iostream> // Start of rational.cpp
#include <string>
using namespace std;
#include "rational.h" Is this necessary?
// default constructor
Rational::Rational() {
SetNumerator(0); Which objects are
SetDenominator(1); being referenced?
}
Example
Rational r; // r = 0/1
Remember
Every class object
Has its own data members
object.member
Specific Constructor
// (numer, denom) constructor
Rational::Rational(int numer, int denom) {
SetNumerator(numer);
SetDenominator(denom);
}
Example
Rational t(2,3); // t = 2/3
SetNumerator(1);
t.SetNumerator(2);
Denominator Mutator
void Rational::SetDenominator(int denom) {
if (denom != 0) {
DenominatorValue = denom;
}
else {
cerr << "Illegal denominator: " << denom
<< "using 1" << endl;
DenominatorValue = 1;
}
}
Example
SetDenominator(5);
Addition Facilitator
Rational Rational::Add(const Rational &r) const {
int a = GetNumerator();
int b = GetDenominator();
int c = r.GetNumerator();
int d = r.GetDenominator();
return Rational(a*d + b*c, b*d);
}
Example
cout << t.Add(u);
Multiplication Facilitator
Rational Rational::Multiply(const Rational &r)
const {
int a = GetNumerator();
int b = GetDenominator();
int c = r.GetNumerator();
int d = r.GetDenominator();
return Rational(a*c, b*d);
}
Example
t.Multiply(u);
Insertion Facilitator
void Rational::Insert(ostream &sout) const {
sout << GetNumerator() << '/' << GetDenominator();
return;
}
Example
t.Insert(cout);
Example
t.Extract(cin);
Auxiliary Arithmetic
Operators
Rational operator+(
const Rational &r, const Rational &s) {
return r.Add(s);
}
Rational operator*(
const Rational &r, const Rational &s) {
return r.Multiply(s);
}
Example
cout << (t + t) * t;
Auxiliary Insertion Operator
ostream& operator<<(
ostream &sout, const Rational &r) {
r.Insert(sout);
return sout;
}
We can do either
t.Extract(cin); // unnatural
cin >> t; // natural
What’s Happening Here?
Suppose the following definitions are in effect
Rational a(2,3);
Rational b(3,4);
Rational c(1,2);
Why do the following statements work
Rational s(a);
Rational t = b;
c = a
C++ has automatically provided us a copy constructor
and an assignment operator
Copy Construction
Default copy construction
Copy of one object to another in a bit-wise manner
SetNumerator(a);
SetDenominator(b);
}
Rational s(a);
Rational t = b;
Gang Of Three
If it is appropriate to define a copy constructor then
Consider also defining
Assignment operator
Copy source to target and return target
A = B = C
Destructor
Clean up the object when it goes out of scope
destructor
A Rational Assignment
Operator
Rational& Rational::operator =(const Rational &r) {
int a = r.GetNumerator();
int b = r.GetDenomiator();
SetNumerator(a);
SetDenominator(b);
*this is C++ syntax for
return *this; the object whose member
} function was invoked
a = b;
a = b = c;
Rational Destructor
Rational::~Rational() {
// nothing to do
}
Arrays
A Mechanism for representing
lists
Apartments
Cassette carrier
Array Terminology
List is composed of elements
Elements in a list have a common name
The list as a whole is referenced through the
common name
List elements are of the same type — the base type
Elements of a list are referenced by subscripting or
indexing the common name
C++ Restrictions
Subscripts are denoted as expressions within brackets: [
]
Base type can be any fundamental, library-defined, or
programmer-defined type
The index type is integer and the index range must be
0 ... n-1
where n is a programmer-defined constant
expression.
Parameter passing style
Always call by reference (no indication necessary)
Basic Array Definition
BaseType Id [ SizeExp ] ;
double X [ 100 ] ;
index
First element of list has index 0
A[0]
Second element of list has index 1, and so on
A[1]
Last element has an index one less than the size of the
list
A[9]
Incorrect indexing is a common error
Array Elements
Suppose
int A[10]; // array of 10 uninitialized ints
A -- -- -- -- -- -- -- -- -- --
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
A -- -- -- -- -- -- -- -- -- --
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Array Element Manipulation
Consider
int i = 7, j = 2, k = 4;
A[0] = 1;
A[i] = 5;
A[j] = A[i] + 3;
A[j+1] = A[i] + A[0];
A[A[j]] = 12;
cin >> A[k]; // where next input value is 3
A 1 -- -- -- -- -- -- -- -- --
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Array Element Manipulation
Consider
int i = 7, j = 2, k = 4;
A[0] = 1;
A[i] = 5;
A[j] = A[i] + 3;
A[j+1] = A[i] + A[0];
A[A[j]] = 12;
cin >> A[k]; // where next input value is 3
A 1 -- -- -- -- -- -- 5 -- --
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Array Element Manipulation
Consider
int i = 7, j = 2, k = 4;
A[0] = 1;
A[i] = 5;
A[j] = A[i] + 3;
A[j+1] = A[i] + A[0];
A[A[j]] = 12;
cin >> A[k]; // where next input value is 3
A 1 -- 8 -- -- -- -- 5 -- --
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Array Element Manipulation
Consider
int i = 7, j = 2, k = 4;
A[0] = 1;
A[i] = 5;
A[j] = A[i] + 3;
A[j+1] = A[i] + A[0];
A[A[j]] = 12;
cin >> A[k]; // where next input value is 3
A 1 -- 8 6 -- -- -- 5 -- --
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Array Element Manipulation
Consider
int i = 7, j = 2, k = 4;
A[0] = 1;
A[i] = 5;
A[j] = A[i] + 3;
A[j+1] = A[i] + A[0];
A[A[j]] = 12;
cin >> A[k]; // where next input value is 3
A 1 -- 8 6 -- -- -- 5 12 --
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Array Element Manipulation
Consider
int i = 7, j = 2, k = 4;
A[0] = 1;
A[i] = 5;
A[j] = A[i] + 3;
A[j+1] = A[i] + A[0];
A[A[j]] = 12;
cin >> A[k]; // where next input value is 3
A 1 -- 8 6 3 -- -- 5 12 --
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Extracting Values For A List
int A[MaxListSize];
int n = 0;
int CurrentInput;
while((n < MaxListSize) && (cin >> CurrentInput)){
A[n] = CurrentInput;
++n;
}
Displaying A List
// List A of n elements has already been set
for (int i = 0; i < n; ++i) {
cout << A[i] << " ";
}
cout << endl;
Smallest Value
Problem
Find the smallest value in a list of integers
Input
A list of integers and a value indicating the number
of integers
Output
Smallest value in the list
Note
List remains unchanged after finding the smallest
value!
Preliminary Design
Realizations
When looking for value with distinguishing
int Number[6];
Number[0] = 3; Number[1] = 88; Number[2] = -7;
Number[3] = 9; Number[4] = 1; Number[5] = 24;
Notice no brackets
int List[3];
List[0] = 9; List[1] = 12; List[2] = 45;
values
Does it matter if
Element values are not necessarily numbers
Major tasks
Comparisons of elements
Bubble sort
Iteratively pass through the list and examining
Quick sort
Divide the list into sublists such that every element
General question
How fast can we sort using the perfect comparison-
based method
The best possible worst case time is proportional
to
n log n time units
Vectors
First-class mechanism for
representing lists
Adapters
priority_queue, queue, and stack
Vector Class Properties
Provides list representation comparable in efficiency to
arrays
First-class type
Efficient subscripting is possible
Indices are in the range 0 … size of list - 1
Iterators
Efficient sequential access
Example
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> A(4, 0); // A: 0 0 0 0
A.resize(8, 2); // A: 0 0 0 0 2 2 2 2
vector<int> B(3, 1); // B: 1 1 1
for (int i = 0; i < B.size(); ++i) {
A[i] = B[i] + 2;
} // A: 3 3 3 0 2 2 2 2
A = B; // A: 1 1 1
return 0;
}
Some Vector Constructors
vector()
The default constructor creates a vector of zero
length
vector(const T &V)
The copy constructor creates a vector that is a
duplicate of vector V.
Shallow copy!
Construction
Container name
Basic construction
vector<T> List;
Base element
type
Example
vector<int> A; // 0 ints
vector<float> B; // 0 floats
vector<Rational> C; // 0 Rationals
Construction
Container name
Basic construction
vector<T> List(SizeExpression);
Number of
elements to be
Base element
default
type
constructed
Example
vector<int> A(10); // 10 ints
vector<float> B(20); // 20 floats
vector<Rational> C(5); // 5 Rationals
int n = PromptAndRead();
vector<int> D(n); // n ints
Construction
Container name
Basic construction Initial
value
vector<T> List(SizeExpression, Value);
Number of
elements to be
Base element
default
type
constructed
Example
vector<int> A(10, 3); // 10 3s
vector<float> B(20, 0.2); // 20 0.2s
Rational r(2/3);
vector<Rational> C(5, r); // 5 2/3s
Vector Interface
size_type size() const
Returns the number of elements in the vector
if (A.empty()) {
// ...
Vector Interface
vector<T>& operator = (const vector<T> &V)
The member assignment operator makes its vector
Lvalue
vector
Rvalue
Example
vector<int> A(4, 0); // A: 0 0 0 0
const vector<int> B(4, 0); // B: 0 0 0 0
vector<int> MyList(3);
cout << "Enter numbers: ";
GetList(MyList);
Examples
void PutList(const vector<int> &A) {
for (int i = 0; i < A.size(); ++i) {
cout << A[i] << endl;
}
}
push_back(const T &val)
Inserts a copy of val after the last element of the
vector
Example
void GetValues(vector<int> &A) {
A.resize(0);
int Val;
while (cin >> Val) {
A.push_back(Val);
}
}
vector<int> List;
cout << "Enter numbers: ";
GetValues(List);
Overloading >>
istream& operator>>(istream& sin, vector<int> &A) {
A.resize(0);
int Val;
while (sin >> Val) {
A.push_back(Val);
}
return sin;
}
vector<int> B;
cout << "Enter numbers: ";
cin >> B;
Vector Interface
reference front()
Returns a reference to the first element of the vector
the vector
vector<int> B(4,1); // B: 1 1 1 1
int& val = B.front();
val = 7; // B: 7 1 1 1
Vector Interface
reference back()
Returns a reference to the last element of the vector
vector
vector<int> C(4,1); // C: 1 1 1 1
int& val = C.back();
val = 5; // C: 1 1 1 5
Iterators
Iterator is a pointer to an element
Really pointer abstraction
Notes
Algorithm component of STL uses iterators
Code using iterators rather than subscripting can
often be reused by other objects using different
container representations
Vector Interface
iterator begin()
Returns an iterator that points to the first element of
the vector
iterator end()
Returns an iterator that points to immediately beyond
the last element of the vector
vector<int> C(4); // C: 0 0 0 0
C[0] = 0; C[1] = 1; C[2] = 2; C[3] = 3;
vector<int>::iterator p = C.begin();
vector<int>::iterator q = C.end();
Iterators
To avoid unwieldy syntax programmers typically use typedef
statements to create simple iterator type names
vector<int> C(4); // C: 0 0 0 0
iterator p = C.begin();
iterator q = C.end();
Iterator Operators
* dereferencing operator
Produces a reference to the object to which the iterator p
points
*p
iterator p = List.begin();
cout << *p; // 100
++p;
cout << *p; // 101
--p;
cout << *p; // 100
reverse_iterator q = List.rbegin();
cout << *q; // 102
++q;
cout << *q; // 101
--q;
cout << *q; // 102
Vector Interface
insert(iterator pos, const T &val = T())
Inserts a copy of val at position pos of the vector
erase(iterator pos)
Removes the element of the vector at position pos
SelectionSort Revisited
void SelectionSort(vector<int> &A) {
int n = A.size();
for (int i = 0; i < n); ++i) {
int k = i;
for (int j = i + 1; j < n; ++j) {
if (A[j] < A[k])
k = j;
}
if (i != k)
swap(A[k], A[i]);
}
}
QuickSort
QuickSort
Divide the list into sublists such that every element in the
IOEPTYURWQ
8…9
EOIPTYURWQ
EOIPTYURWQ 7…9 8…7
EIOPTYURWQ
5…9 7…6
EIOPTYURWQ
EIOPTYURWQ 4…9 5…5
EIOPQYURWT
4…3
EIOPQYURWT
EIOPQRTUWY 0…9 2…2
EIOPQRTUWY
EIOPQRTUWY 1…2
Solution
Binary search
A[i] is a vector<int>
i can vary from 0 to A.size() - 1
A[i][j] is a int
j can vary from 0 to A[i].size() - 1
Multi-Dimensional Arrays
Syntax
btype mdarray[size_1][size_2] ... [size_k]
Where
k - dimensional array
Semantics
mdarray is an object whose elements are indexed by
a sequence of k subscripts
the i-th subscript is in the range 0 ... size_i - 1
Memory Layout
-- ... -- -- ... --
M[0][0] M[0][3] M[1][0] M[1][3]
Identity Matrix Initialization
const int MaxSize = 25;
float A[MaxSize][MaxSize];
int nr = PromptAndRead();
int nc = PromptAndRead();
assert((nr <= MaxSize) && (nc <= MaxSize));
for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
A[r][c] = 0;
}
A[r][r] = 1;
}
Matrix Addition Solution
Notice only first
brackets are empty
A Graphical Application
Programmer Interface
Mouse up
C : SimpleWindow User start
Key down
Mouse click
Key up
Timer
Handle messages by
registering a call back
EzWindows Coordinate
System
Use centimeters X coordinate: distance Y coordinate:
from left edge of distance from top
Metric screen (4 cm) of screen (4 cm)
Simpler to understand
Helps introduce
notion
of information hiding
or encapsulation
window manager.
Class SimpleWindow
Writing text in a window
void SimpleWindow::RenderText(const Position
&UpperLeft, const Position &LowerRight,
const string &Msg = "Message",
const color &TextColor = Black,
const color &BackGroundColor = White)
First coordinate of the
bounding box
Message
Second coordinate of
the bounding box
Hello EzWindows
#include <assert.h>
#include "ezwin.h"
// Create a 10 x 4 window
SimpleWindow HelloWindow("Hello EzWindows",
10.0, 4.0, Position(5.0, 6.0));
return 0;
}
Hello EzWindows
// ApiEnd(): shutdown the window
int ApiEnd() {
HelloWindow.Close();
return 0;
}
Class SimpleWindow
Simple Window constructor
SimpleWindow::SimpleWindow(
const string &t =
"Untitled“
float w = 8,
float h = 8,
const Position &p = Position(0,0)
)
Bitmaps
Class BitMap
Uses BitMapStatus
enum BitMapStatus {
NoBitMap, BitMapOkay, NoWindow
};
Class BitMap
Class BitMap can display .bmp files in a SimpleWindow
window
BitMap’s constructor is
BitMap::BitMap(SimpleWindow &w)
occurs
Registering a callback
W1.SetMouseClickCallback(f);
successfully started
A return value of 1 indicates success
set up
void SimpleWindow::StopTimer()
Turns timer off
#include <assert.h>
#include "bitmap.h“ Example
SimpleWindow W1("Fun", 15.0, 9.0, Position(1.0, 1.0));
graphical interfaces
modified
Rvalue expressions
Represent objects that can only be evaluated
Consider
int a;
vector<int> b(3);
int c[3];
a = 1; // a: lvalue
c[0] = 2*a + b[0]; // c[0], a, b[0]: lvalues
Observation
Not all lvalues are the names of objects
Basics
Pointer
Object whose value represents the location of
another object
In C++ there are pointer types for each type of
object
Pointers to int objects
int i = 1;
int *ptr = &i; // ptr points to i
*ptr = 2;
cout << i << endl; // display a 2
* indicates indirection or dereferencing
*ptr is an lvalue
Address Operator
& use is not limited to definition initialization
int i = 1;
int j = 2;
int *ptr;
ptr = &i; // ptr points to location of i
*ptr = 3; // contents of i are updated
ptr = &j; // ptr points to location of j
*ptr = 4; // contents of j are updated
cout << i << " " << j << endl;
Null Address
0 is a pointer constant that represents the empty or null
address
Its value indicates that pointer is not pointing to a
valid object
Cannot dereference a pointer whose value is null
int *ptr = 0;
cout << *ptr << endl; // invalid, ptr
// does not point to
// a valid int
Member Indirection
Consider
Rational r(4,3);
Rational rPtr = &r;
To select a member of r using rPtr and member selection,
operator precedence requires
Invokes member Insert() of
the object to which rPtr
(*rPtr).Insert(cout); points (r)
This syntax is clumsy, so C++ provides the indirect
member selector operator ->
rPtr->Insert(cout);
Invokes member Insert() of
the object to which rPtr
points (r)
Traditional Pointer Usage
void IndirectSwap(char *Ptr1, char *Ptr2) {
char c = *Ptr1;
*Ptr1 = *Ptr2;
*Ptr2 = c;
} In C, there are no reference
parameters. Pointers are
int main() {
used to simulate them.
char a = 'y';
char b = 'n';
IndirectSwap(&a, &b);
cout << a << b << endl;
return 0;
}
Constants and Pointers
A constant pointer is a pointer such that we cannot
change the location to which the pointer points
char c = 'c';
const char d = 'd';
char * const ptr1 = &c;
ptr1 = &d; // illegal
A pointer to a constant value is a pointer object such
that the value at the location to which the pointer points
is considered constant
const char *ptr2 = &d;
*ptr2 = 'e'; // illegal: cannot change d
// through indirection with ptr2
Differences
Local objects and Dynamic object
objects
parameters
Object memory is Object memory is
acquired acquired by program
automatically with an allocation
request
new operation
Object memory is Dynamic objects can
returned exist beyond the
automatically when function in which they
object goes out of were allocated
scope Object memory is
returned by a
deallocation request
delete operation
General New Operation
Behavior
Memory for dynamic objects
Requested from the free store
Beware
The newly acquired memory is uninitialized unless
iptr —
rptr 0/1
Initialization
The newly acquired memory is initialized using a
SomeType constructor
ParameterList provides the parameters to the
constructor
Examples
int *iptr = new int(10);
Rational *rptr = new Rational(1,2);
iptr 10
rptr 1/2
The Primary New Form
Syntax
A — 5 —
R 2/3 0/1
Right Array For The Job
cout << "Enter list size: ";
int n;
cin >> n;
int *A = new int[n];
GetList(A, n);
SelectionSort(A, n);
DisplayList(A, n);
Note
Use of the container classes of the STL is preferred
from a software engineering viewpoint
Example vector class
Delete Operators
Forms of request
delete [] A;
A —
?
B
Memory Leak Pitfall
int *A = new int [5];
for (int i = 0; i < 5; ++i) A[i] = i;
A 0 1 2 3 4
A 0 1 2 3 4
— — — — —
A Simple Dynamic List Type
What we want
An integer list data type IntList with the basic
features of the vector data type from the Standard
Template Library
public:
// inspector for element of constant list
const int& operator[](int i) const;
// inspector/mutator for element of
// nonconstant list
int& operator[](int i);
// resize list
void resize(int n = 0, int val = 0);
// convenience for adding new last element
void push_back(int val);
IntList Definition (continued)
private:
// data members
int *Values; // pointer to elements
int NumberValues; // size of list
};
Then
B[2] is changed!
Not what a client would expect
Implication
Must use tailored copy constructor
Tailored Copy Constructor
IntList::IntList(const IntList &A) {
NumberValues = A.size();
Values = new int [size()];
assert(Values);
for (int i = 0; i < size(); ++i)
Values[i] = A[i];
}
memory leak
IntList::~IntList() {
delete [] Values;
}
First Assignment Attempt
Algorithm
Return existing dynamic memory
Acquire sufficient new dynamic memory
Copy the size and the elements of the source object
to the target element
Initial Implementation
(Wrong)
IntList& operator=(const IntList &A) {
NumberValues = A.size();
delete [] Values;
Values = new int [NumberValues ];
assert(Values);
for (int i = 0; i < A.size(); ++i)
Values[i] = A[i];
return A;
}
IntList::size() {
return NumberValues;
}
or equivalently
IntList::size() {
return this->NumberValues;
}
Member Assignment
Operator
IntList& IntList::operator=(const IntList &A) {
if (this != &A) {
delete [] Values;
NumberValues = A.size();
Values = new int [A.size()];
assert(Values);
for (int i = 0; i < A.size(); ++i) {
Values[i] = A[i];
}
}
return *this; Notice the different uses
} of the subscript operator
Why the
asterisk?
Accessing List Elements
// Compute an rvalue (access constant element)
const int& IntList::operator[](int i) const {
assert((i >= 0) && (i < size()));
return Values[i];
}
// Compute an lvalue
int& IntList::operator[](int i) {
assert((i >= 0) && (i < size()));
return Values[i];
}
Stream Operators
Should they be members?
class IntList {
// ...
ostream& operator<<(ostream &sout);
// ...
};
Answer is based on the form we want the operation to
take
IntList A(5,1);
A << cout; // member form (unnatural)
cout << A; // nonmember form (natural)
Beware of Friends
If a class needs to
Can provide complete access rights to a nonmember
Declaration example
class IntList {
// ...
friend ostream& operator<< (
ostream &sout, const IntList &A);
// ...
};
Implementing Friend <<
ostream& operator<<(ostream &sout,
const IntList &A){
sout << "[ ";
for (int i = 0; i < A.NumberValues; ++i) {
sout << A.Values[i] << " ";
}
sout << "]";
Is there any need for
return sout; this friendship?
}
Proper << Implementation
ostream& operator<<(ostream &sout,
const IntList &A){
sout << "[ ";
for (int i = 0; i < A.size(); ++i) {
sout << A[i] << " ";
}
sout << "]";
return sout;
}
Inheritance
Mechanism for deriving new
classes from existing classes
Moving bitmaps
specialized version
of the parent class Bicycle
is-a relationships
of
programming
Terminology
Base class (superclass) Bicycle
Height Height
TriangleShape
#include "shape.h"
class TriangleShape : public Shape {
public:
TriangleShape(SimpleWindow &w,
const Position &p, const color &c = Red,
float slen = 1);
float GetSideLength() const;
void SetSize(float slen);
void Draw();
private:
float SideLength;
};
#include "shape.h"
EllipseShape
class EllipseShape : public Shape {
public:
EllipseShape(SimpleWindow &w,
const Position &Center,
const color &c = Red, float Width = 1,
float Height = 2);
float GetWidth() const;
float GetHeight() const;
void Draw();
void SetSize(float Width, float Height);
private:
float Width;
float Height;
};
RectangleShape
#include "shape.h"
class RectangleShape : public Shape {
public:
RectangleShape(SimpleWindow &w,
const Position &Center, const color &c =
Red,
float Width = 1, float Width = 2);
float GetWidth() const;
float GetHeight() const;
void Draw();
void SetSize(float Width, float Height);
private:
float Width;
float Height;
};
TriangleShape::Draw()
void TriangleShape::Draw() {
const float Pi = 3.1415;
const Position Center = GetPosition();
const float SLength = GetSideLength();
int ApiEnd()
TWindow.Close();
return 0;
}
Inheritance and Member
Access
class SomeClass {
public:
void MemberFunction();
int MyPublicData;
protected:
int MyProtectedData;
private:
int MyPrivateData;
};
void SomeClass::MemberFunction() {
MyPublicData = 1; // access allowed
MyProtectedData = 2; // access allowed
MyPrivateData = 3; // access allowed
}
Inheritance and Member
Access
void NonMemberFunction() {
SomeClass C;
C.MyPublicData = 1; // access allowed
C.MyProtectedData = 2; // illegal
C.MyPrivateData = 3; // illegal
}
Inheritance and Member
Access
class BaseClass {
public: int MyPublicData;
protected: int MyProtectedData;
private: int MyPrivateData;
};
class DerivedClass : public BaseClass {
public: void DerivedClassFunction();
// ...
};
void DerivedClass::DerivedClassFunction() {
MyPublicData = 1; // access allowed
MyProtectedData = 2; // access allowed
MyPrivateData = 3; // illegal
}
Controlling Inheritance
Inheritance Type Base class member Derived class
access member access
public public
public protected protected
private inaccessible
public protected
protected protected protected
private inaccessible
public private
private protected private
private inaccessible
Templates and
Polymorphism
Generic functions and classes
different types
The action taken depends upon the types of the
objects
Primitive polymorphism
Polymorphic Functions
Templates
Generate a function or class at compile time
True polymorphism
Choice of which function to execute is made during
run time
C++ uses virtual functions
Function Templates
Current scenario
We rewrite functions Min(), Max(), and
Function template
Describes a function format that when instantiated
Need
Draw() to be a virtual function
Placeholder in the Shape class with specialized
Virtual Functions
For virtual functions
It is the type of object to which the pointer refers
Introduces overhead
Pure Virtual Function
Has no implementation