Basics
Machine, software, and program
design
JPC and JWD © 2002 McGraw-Hill, Inc.
Computer Organization
CPU - central processing unitMemory
Input devices
Output devices
CPU - central processing unit
Where decisions are made, computations are performed, and input/output requests are delegated
Memory
Stores information being processed by the CPU Input devices
Allows people to supply information to computers Output devices
Computer Organization
Memory CPU Input Devices Output DevicesCPU
Brainsof the computer
Arithmetic calculations are performed using the Arithmetic/Logical Unit or ALU
Control unit decodes and executes instructions
Arithmetic operations are performed using binary number system
Control Unit
The fetch/execute cycle is the steps the CPU takes to execute an instruction Performing the action specified by an instruction is known as executing the instruction
The program counter (PC) holds the memory address of the next instruction
Fetch the instruction to which the PC points
Increment the PC
Execute the fetched instruction
Input and Output Devices
Accessories that allow computer to perform specific tasks Receive information for processing
Return the results of processing Store information
Accessories that allow computer to perform specific tasks Receive information for processing
Return the results of processing Store information
Common input and output devices
Speakers Mouse Scanner
Printer Joystick CD-ROM
Keyboard Microphone DVD
Accessories that allow computer to perform specific tasks Receive information for processing
Return the results of processing Store information
Common input and output devices
Speakers Mouse Scanner
Printer Joystick CD-ROM
Keyboard Microphone DVD
Some devices are capable of both input and output
Monitor
Display device that operates like a television Also known as CRT (cathode ray tube)
Controlled by an output device called a graphics card Displayable area
Measured in dots per inch, dots are often referred to as
pixels (short for picture element)
Standard resolution is 640 by 480 Many cards support
resolution of 1280 by 1024 or better
Number of colors supported varies from 16 to billions 1280 pixels across screen 1024 pixels down screen Application software
Programs designed to perform specific tasks that are transparent to the user
System software
Programs that support the execution and development of other programs
Two major types
Operating systems
Translation systems
Software
Application Software
Application software is the software that has made using computers indispensable and popular
Common application software Word processors
Desktop publishing programs Spreadsheets
Presentation managers Drawing programs
Application software is the software that has made using computers indispensable and popular
Common application software Word processors
Desktop publishing programs Spreadsheets
Presentation managers Drawing programs
Learning how to develop application software is our focus
Examples
Windows®, UNIX®, Mac OS X®
Controls and manages the computing resources Important services that an operating system provides
File system
Directories, folders, files
Commands that allow for manipulation of the file system
Sort, delete, copy
Ability to perform input and output on a variety of devices
Operating System
Translation System
Set of programs used to develop software
A key component of a translation system is a translator Some types of translators
Compiler
Converts from one language to another Linker
Combines resources Examples
Microsoft Visual C++®, CBuilder®, g++, Code Warrior®
Performs compilation, linking, and other activities.
Software Development Activities
EditingCompiling
Linking with precompiled files Object files
Library modules Loading and executing
Software Development Cycle
Compile Link
Library routines Other object files Think Edit Load Execute Source Program
IDEs
Integrated Development Environments or IDEs Supports the entire software development cycle
E.g., MS Visual C++, Borland, Code Warrior
Provides all the capabilities for developing software Editor Compiler Linker Loader Debugger Viewer
Engineering Software
Software engineering Area of computer science concerned with building large software systems
Challenge
Tremendous advances in hardware have not been accompanied by comparable advances in software
Complexity Trade-off
System complexity tends to grow as the system becomes more user friendly High Low Complexity Total Software Complexity User Simplicity
Software Engineering Goals
Reliability Understandability Cost Effectiveness Adaptability Reusability Reliability An unreliable life-critical system can be fatal Understandability
Future development is difficult if software is hard to understand Cost Effectiveness
Cost to develop and maintain should not exceed profit Adaptability
System that is adaptive is easier to alter and expand Reusability
Improves reliability, maintainability, and profitability
Abstraction
Extract the relevant properties while ignoring inessentials Encapsulation
Hide and protect essential information through a controlled interface
Modularity
Hierarchy Abstraction
Extract the relevant properties while ignoring inessentials Encapsulation
Hide and protect essential information through a controlled interface
Modularity
Dividing an object into smaller modules so that it is easier to understand and manipulate
Hierarchy Abstraction
Extract the relevant properties while ignoring inessentials Encapsulation
Hide and protect essential information through a controlled interface
Modularity
Dividing an object into smaller modules so that it is easier to understand and manipulate
Hierarchy
Ranking or ordering of objects based on some relationship between them
Software Engineering Principles
AbstractionEncapsulation
Modularity
Hierarchy Abstraction
Extract the relevant properties while ignoring inessentials Encapsulation
Modularity
Extract the relevant object properties while ignoring inessentials Defines a view of the object
Example - car
Car dealer views a car from selling features standpoint
Price, length of warranty, color, …
Mechanic views a car from systems maintenance standpoint
Size of the oil filter, type of spark plugs, …
Abstraction
Price? Oil change?
Encapsulation
Steps Decompose an object into parts Hide and protect essential information
Supply interface that allows information to be modified in a controlled and useful manner
Internal representation can be changed without affecting other system parts
Example - car radio
Interface consists of controls and power and antenna connectors
The details of how it works is hidden To install and use a radio
Modularity
Dividing an object into smaller pieces or modules so that the object is easier to understand and manipulate
Most complex systems are modular
Example - Automobile can be decomposed into subsystems Cooling system
Radiator Thermostat Water pump
Ignition system
Battery Starter Spark plugs
Hierarchy
Hierarchy Ranking or ordering of objects based on some relationship between them
Help us understand complex systems
Example - a company hierarchy helps employees understand the company and their positions within it
For complex systems, a useful way of ordering similar abstractions is a taxonomy from least general to most general
Northern Timber Wolf Taxonomy
Kingdom Animalia Phylum Chordata Class Mammalia Order Carnivora Family Caninae Genus CanisSpecies Canis lupus
Subspecies Canis lupus occidentalis Northern Timber Wolf
OO Design and Programming
Object-oriented design and programming methodology supports good software engineering
Promotes thinking in a way that models the way we think and interact with the real world
Example - watching television
The remote is a physical object with properties
Weight, size, can send message to the television
The television is also a physical object with various properties
Objects
An object is almost anything with the following characteristics Name
Properties
The ability to act upon receiving a message
Basic message types
Directive to perform an action
Request to change one of its properties
The individual digits of a binary number are referred to as bits Each bit represents a power of two
01011 = 0 • 24 + 1 • 23 + 0 • 22 + 1 • 21 + 1 • 20 = 11 00010 = 0 • 24 + 0 • 23 + 0 • 22 + 1 • 21 + 0 • 20 = 2
Binary Arithmetic
00010 + 01011 Binary addition 2 + 11 EquivalentdecimalBinary Arithmetic
5 × 3 15 Equivalent decimal multiplication 0101 × 0011 0101 0101 0000 0000 0001111 Binary multiplicationTwo’s Complement
Representation for signed binary numbers Leading bit is a sign bit
Binary number with leading 0 is positive Binary number with leading 1 is negative
Magnitude of positive numbers is just the binary representation Magnitude of negative numbers is found by
Complement the bits
Replace all the 1's with 0's, and all the 0's with 1's Add one to the complemented number
Two’s Complement
Performing two's complement on the decimal 7 to get -7 Using a five-bit representation
7 = 00111 Convert to binary 11000 Complement the bits 11000 Add 1 to the complement + 00001
11001 Result is -7 in two's complement
Two's Complement Arithmetic
Computing 8 - 7 using a two's complement representation with five-bit numbers 8 - 7 = 8 + (-7) = 1 01000 Two's complement of 8 11001 Two's complement of -7 01000 Add 8 and -7 + 11001 100001 Throw away thehigh-order carry as we are
Fundamentals of C++
Basic programming elements and
concepts
JPC and JWD © 2002 McGraw-Hill, Inc.
Program statement Definition Declaration Action Executable unit
Named set of program statements
Different languages refer to executable units by different names
Subroutine: Fortran and Basic
Procedure: Pascal
Function : C++
Program Organization
C++ program Collection of definitions, declarations and functions Collection can span multiple files
Advantages
Structured into small understandable units Complexity is reduced
Overall program size decreases
Object
Object is a representation of some information Name
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 Object changes one of its properties
// Program: Display greetings // Author(s): Ima Programmer // Date: 1/24/2001
#include <iostream> #include <string> using namespace std; int main() {
cout << "Hello world!" << endl; return 0;
}
A First Program - Greeting.cpp
Preprocessor directives
Insertion statement Ends executions
of main() which ends program Comments Function Function named main() indicates start of program
Provides simple access
Definitions Extraction Definition with initialization
Area.cpp
#include <iostream> using namespace std; int main() {// Extract length and width
cout << "Rectangle dimensions: "; float Length;
float Width;
cin >> Length >> Width;
// Compute and insert the area
float Area = Length * Width;
cout << "Area = " << Area << " = Length " << Length << " * Width " << Width << endl; return 0;
}
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) /* long comment */(save for debugging) Typical uses
Identify program and who wrote it Record when program was written Add descriptions of modifications
Fundamental C++ Objects
C++ has a large number of fundamental or built-in object types The fundamental object types fall into one of three categories
Integer objects Floating-point objects Character objects
1
1.28345
Z
5
P
3.14
Integer Object Types
The basic integer object type is int The size of an intdepends on the machine and the
compiler
On PCs it is normally 16 or 32 bits
Other integers object types short: typically uses less bits
long: typically uses more bits
Different types allow programmers to use resources more efficiently
Standard arithmetic and relational operations are available for these types
Integer Constants
Integer constants are positive or negative whole numbers Integer constant forms
Decimal 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 40000L 50000 23a (illegal)The type of the constant depends on its size, unless the type specifier is used
Character Object Types
Character type charis related to the integer typesCharacters are encoded using a scheme where an integer represents a particular character
ASCII is the dominant encoding scheme Examples
' 'encoded as 32 '+'encoded as 43 'A'encoded as 65 'Z'encoded as 90 'a'encoded as 97 'z'encoded as 122
Appendix A gives the complete ASCII character set
Character Operations
Arithmetic and relational operations are defined for characters types
'a' < 'b'is true
'4' > '3' is true
Character Constants
Explicit (literal) characters within single quotes
'a','D','*'
Special characters - delineated by a backslash \ Two character sequences (escape codes) Some important special escape codes
\tdenotes a tab \ndenotes a new line \\denotes a backslash \'denotes a single
quote
\"denotes a double quote
'\t'is the explicit tab character, '\n'is the explicit new line
character, and so on
Literal String Constants
A literal string constant is a sequence of zero or more characters enclosed in double quotes
"We are even loonier than you think"
"Rust never sleeps\n"
"Nilla is a Labrador Retriever"
Floating-Point Object Types
Floating-point object types represent real numbers Integer part Fractional part
The number 108.1517 breaks down into the following parts 108 - integer part
1517 - fractional part
C++ provides three floating-point object types
float
double
long double
Floating-Point Constants
Standard decimal notation134.123 0.15F
Standard scientific notation 1.45E6
0.979e-3L
When not specified, floating-point constants are of type double
F or f indicates single precision floating point value
L or l indicates long double floating point value
Names
Used to denote program values or components A valid name is a sequence of
Letters (upper and lowercase) Digits
A name cannot start with a digit Underscores
A name should not normally start with an underscore
Names are case sensitive
MyObject is a different name than MYOBJECT There are two kinds of names
Keywords Identifiers
Keywords
Keywords are words reserved as part of the language int, return, float, double
They cannot be used by the programmer to name things They consist of lowercase letters only
Identifiers
Identifiers should be Short enough to be reasonable to type (single word is norm)
Standard abbreviations are fine (but only standard
abbreviations)
Long enough to be understandable
When using multiple word identifiers capitalize the first letter of each word
Examples Min Temperature CameraAngle CurrentNbrPoints
Definitions
All objects that are used in a program must be defined An object definition specifies
Type Name
General definition form
Type Id, Id, ..., Id;
Known type
List of one or more identifiers
Examples
char Response; int MinElement; float Score; float Temperature; int i; int n; char c; float x;Objects are uninitialized with this definition form
(Value of a object is whatever is in its
assigned memory location)
Arithmetic Operators
Common Addition + Subtraction - Multiplication * Division / Mod % Note No exponentiation operator Single division operator Operators are overloaded to work with more than one type of object
Write m*x + b
Integer Division
Integer division produces an integer result Truncates the result
Examples
3 / 2evaluates to 1
4 / 6evaluates to 0
10 / 3evaluates to 3
Mod
Produces the remainder of the division Examples
5 % 2evaluates to 1
12 % 4evaluates to 0
Operators and Precedence
Consider mx + bConsider 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
Better idea to specify its desired value at the same time Exception is when the next statement is an extraction for
the object
Remember our convention of one definition per statement!
Examples
int FahrenheitFreezing = 32; char FinalGrade = 'A';
cout << "Slope of line: "; float m;
cin >> m;
cout << "Intercept: "; float b;
cin >> b;
cout << "X value of interest: "; float x;
cin >> x;
Modifying Objects
Operators and Expressions
JPC and JWD © 2002 McGraw-Hill, Inc.
Memory Depiction
float y = 12.5; 12.5 y 1001 1002 1003 1004Memory Depiction
float y = 12.5; int Temperature = 32; 12.5 32 y Temperature 1001 1002 1003 1004 1005 1006Memory Depiction
float y = 12.5; int Temperature = 32; char Letter = 'c'; 12.5 32 'c' y Temperature Letter 1001 1002 1003 1004 1005 1006 1007Memory Depiction
float y = 12.5; int Temperature = 32; char Letter = 'c'; int Number; 12.5 32 'c' y Temperature Letter 1001 1002 1003 1004 1005 1006 1007-Number 10081009
Assignment Statement
Basic form object= expression; Celsius = (Fahrenheit - 32) * 5 / 9; y = m * x + b; Action Expression is evaluated Expression value stored in object
Definition
int NewStudents = 6; NewStudents 6
Definition
int NewStudents = 6; int OldStudents = 21; 6 21 NewStudents OldStudentsDefinition
int NewStudents = 6; int OldStudents = 21; int TotalStudents; 6 21 NewStudents OldStudents -TotalStudentsAssignment Statement
int NewStudents = 6; int OldStudents = 21; int TotalStudents;TotalStudents = NewStudents + OldStudents; 6 21 NewStudents OldStudents ? TotalStudents
Assignment Statement
int NewStudents = 6; int OldStudents = 21; int TotalStudents;
TotalStudents = NewStudents + OldStudents; 6 21 NewStudents OldStudents 27 TotalStudents
Assignment Statement
int NewStudents = 6; int OldStudents = 21; int TotalStudents;TotalStudents = NewStudents + OldStudents;
OldStudents = TotalStudents; 6 ? NewStudents OldStudents 27 TotalStudents
Assignment Statement
int NewStudents = 6; int OldStudents = 21; int TotalStudents;
TotalStudents = NewStudents + OldStudents;
OldStudents = TotalStudents; 6 27 NewStudents OldStudents 27 TotalStudents
Consider
Consider
int Value1 = 10; int Value2 = 20; 10 20 Value1 Value2Consider
int Value1 = 10; int Value2 = 20; int Hold = Value1;10 20 Value1 Value2 10 Hold
Consider
int Value1 = 10; int Value2 = 20; int Hold = Value1;
Value1 = Value2; ? 20 Value1 Value2 10 Hold
Consider
int Value1 = 10; int Value2 = 20; int Hold = Value1;Value1 = Value2; 20 20 Value1 Value2 10 Hold
Consider
int Value1 = 10; int Value2 = 20; int Hold = Value1;
Value1 = Value2; Value2 = Hold; 20 ? Value1 Value2 10 Hold
Consider
int Value1 = 10; int Value2 = 20; int Hold = Value1;Value1 = Value2;
Value2 = Hold;
We swappedthe values of objects Value1 and Value2 using Hold as temporary holder for Value1’s starting value!
20 10 Value1 Value2 10 Hold
Incrementing
int i = 1; i 1Incrementing
int i = 1; i = i + 1;Assign the value of expression i + 1to i
Evaluates to 2
i 1
2 i
Const Definitions
Modifier constindicates that an object cannot be changed
Object is read-only
Useful when defining objects representing physical and mathematical constants
const float Pi = 3.1415;
Value has a name that can be used throughout the program
const int SampleSize = 100;
Makes changing the constant easy
Only need to change the definition and recompile
Assignment Conversions
Floating-point expression assigned to an integer object is truncated
Integer expression assigned to a floating-point object is converted to a floating-point value
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
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 membersthat represent attributes and values Member functionsfor object inspection and manipulation Members are accessed using the selection operator (.)
j = s.size();
Auxiliaryfunctions for other behaviors
Libraries often provide special-purpose types and classes Programmers can also define their own types and classes
Examples
Standard Template Library (STL) provides class string
EzWindows library provides several graphical types and classes
SimpleWindowis a class for creating and manipulating
window objects
RectangleShapeis a class for creating and manipulating
Class string
Class string Used to represent a sequence of characters as a 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
using namespace std; // std contains string string s = "Sharp";
EzWindows Library Objects
Definitions are the same form as other objects ExampleSimpleWindow W;
Most non-fundamental classes have been created so that an object is automatically initialized to a sensible value
SimpleWindowobjects have member functions to process
messages to manipulate the objects
Most important member function is Open()which causes
the object to be displayed on the screen
Example
W.Open();
Initialization
Class objects may have several attributes to initialize Syntax for initializing an object with multiple attributes
Type Identifier(Exp1, Exp2, ..., Expn);
SimpleWindow object has several optional attributes
SimpleWindow W("Window Fun", 8, 4);
First attribute
Window banner Second attribute
Width of window in centimeters Third attribute
An EzWindows Program
#include <iostream>using namespace std; #include "ezwin.h" int ApiMain() {
SimpleWindow W("A Window", 12, 12); W.Open();
cout << "Enter a character to exit" << endl; char a;
cin >> a;
return 0; }
An EzWindows Project File
RectangleShape Objects
EzWindows also provides RectangleShapefor manipulating
rectangles
RectangleShapeobjects can specify the following attributes
SimpleWindowobject 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
coloris an EzWindows type
RectangleShape Objects
ExamplesSimpleWindow W1("My Window", 20, 20);
SimpleWindow W2("My Other Window", 15, 10);
RectangleShape R(W1, 4, 2, Blue, 3, 2); RectangleShape S(W2, 5, 2, Red, 1, 1); RectangleShape T(W1, 3, 1, Black, 4, 5); RectangleShape U(W1, 4, 9);
RectangleShape Objects
Some RectangleShapemember functions for processing
messages
Draw()
Causes rectangle to be displayed in its associated window
GetWidth()
Returns width of object in centimeters
GetHeight()
Returns height of object in centimeters
SetSize()
Takes two attributes -- a width and height -- that are used to reset dimensions of the rectangle
Another EzWindows Program
#include <iostream> using namespace std; #include "rect.h"
int ApiMain() {
SimpleWindow W("Rectangular Fun", 12, 12); W.Open();
RectangleShape R(W, 5.0, 2.5, Blue, 1, 2); R.Draw();
cout << "Enter a character to exit" << endl; char Response;
cin >> Response; return 0;
Sample Display Behavior
Compound Assignment
C++ has a large set of operators for applying an operation to an object and then storing the result back into the object 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
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
JPC and JWD © 2002 McGraw-Hill, Inc.
Boolean Algebra
Logical expressions have the one of two values - true or false A rectangle has three sides
The instructor has a pleasant smile
The branch of mathematics is called Boolean algebra
Developed by the British mathematician George Boole in the 19th century
Three key logical operators And
Or Not
Boolean Algebra
Truth tables Lists all combinations of operand values and the result of the operation for each combination
Example
P Q P and Q
False False False
False True False
True False False
True True True
Boolean Algebra
Or truth tableP Q P or Q
False False False
False True True
True False True
Boolean Algebra
Not truth tableP not P
False True True False
Boolean Algebra
Can create complex logical expressions by combining simple logical expressions
Example
not (P and Q)
A truth table can be used to determine when a logical expression is true
P Q P and Q not (P and Q)
False False False True
False True False True
A Boolean Type
C++ contains a type named bool
Type boolhas two symbolic constants
true
false
Boolean operators
The andoperator is &&
The oroperator is ||
The notoperator is !
Warning
&and |are also operators so be careful what you type
A Boolean Type
Example logical expressionsbool 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; bool p = (i < 10); bool q = (k > i); bool r = (i >= k);Operator Precedence Revisited
Precedence of operators (from highest to lowest) Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment
Operator Precedence Revisited
ConsiderOperator Precedence Revisited
Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
Yuck! Do not write expressions like this!
Operator Precedence Revisited
Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))
||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) ||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) ||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) ||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) ||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) ||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) ||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) ||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
However, for your information it is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) ||
((!false) == (5 < 24))
Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
Conditional Constructs
Provide Ability to control whether a statement list is executed Two constructs If statement if if-else if-else-ef Switch statement
Left for reading
The Basic If Statement
Syntaxif (Expression)
Action
If the Expressionis true then execute Action
Actionis either a single statement or a group of statements within braces
Expression
Action
Example
if (Value < 0) { Value = -Value; } Value < 0 Value = -Value true falseIs our number negative?
If Value is not less than zero then our number is fine as is If Value is less than
zero then we need to update its value to that of its additive
inverse
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
value2 < value1
int rememberValue1 = value1 value1 = value2
value2 = rememberValue1
true false
Are the numbers out of order
Rearrange value1 and value2 to put their values
in the proper order
The numbers were initially in order
The numbers were rearranged into the
proper order
The numbers are in order
What is the Output?
int m = 5; int n = 10; if (m < n) ++m; ++n; cout << " m = " << m << " n = " n << endl;
The If-Else Statement
Syntax if (Expression) Action1 else Action2If Expressionis true then execute Action1otherwise execute Action2
if (v == 0) { cout << "v is 0"; } else { cout << "v is not 0"; } Expression Action1 Action2 true false
Finding the Max
cout << "Enter two integers: "; int Value1;
int Value2;
cin >> Value1 >> Value2; int Max; if (Value1 < Value2) { Max = Value2; } else { Max = Value1; }
Finding the Max
Value1 < Value2
Max = Value2 Max = Value1
true false
Is Value2 larger than Value1 Yes, it is . So Value2 is
larger than Value1. In this case, Max is set
to Value2
No, its not. So Value1 is at least as large as
Value2. In this case, Max is set to Value1
Either case, Max is set correctly
Selection
It is often the case that depending upon the value of an expression we want to perform a particular action Two major ways of accomplishing this choice
if-else-if statement
if-else statements “glued” together Switch statement
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
JPC and JWD © 2002 McGraw-Hill, Inc.
Determining Average Magnitude
Suppose we want to calculate the average apparent brightness of a list of five star magnitude values Can we do it?
Yes, it would be easy
Suppose we want to calculate the average apparent brightness of a list of five star magnitude values
Can we do it
Yes, it would be easy
Suppose we want to calculate the average apparent brightness of a list of 8,479 stars visible from earth
Can we do it
Yes, but it would be gruesome without the use of iteration
C++ Iterative Constructs
Three constructs while statement for statement do-while statementWhile Syntax
Logical expression that determines whether the action is to be executed
while ( Expression ) Action
Action to be iteratively performed until logical
expression is false
While Semantics
Expression Action true false Expression is evaluated at the start of each iteration of the loop If Expression is true, Action is executed If Expression is false, program execution continues with next statementComputing 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;
Execution Trace
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
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;
numberProcessed
Suppose input contains: 1 5 3 1 6
4 listSize 0Execution Trace
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;
numberProcessed sum
Suppose input contains: 1 5 3 1 6
4listSize
0 0
Execution Trace
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;
numberProcessed sum
Suppose input contains: 1 5 3 1 6
4 listSize 0 0Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4listSize
0 0
--Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 0 0 1Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 0 0 1 1Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 0 1 1 1Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4listSize
1 1 1
Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 1 1--Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4listSize
1 1 5
Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 1 1 5 6Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 1 6 5 2Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 2 6 5 6Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 2 6 --2Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 2 6 3 2Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 2 6 3 9Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 2 9 3 3Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 3 9 3 3Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 3 9 --3Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 3 9 1 3Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 3 9 1 10Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 3 10 1 4Execution Trace
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;
numberProcessed sum value
Suppose input contains: 1 5 3 1 6
4 listSize 3 10 1 4Execution Trace
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; numberProcessed
sum
Suppose input contains: 1 5 3 1 6
4 listSize 3 10 average 2.5 4Execution Trace
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;
numberProcessed sum average
Suppose input contains: 1 5 3 1 6
4 listSize 3 10 2.5 4Execution Trace
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
Stays in stream until
extracted
Power of Two Table
const int TableSize = 20;
int i = 0; long Entry = 1;
cout << "i" << "\t\t" << "2 ** i" << endl;
while (i < TableSize) {
cout << i << "\t\t" << Entry << endl; Entry = 2 * Entry;
++i; }
Better Way of Averaging
int numberProcessed = 0; double sum = 0;
double value;
while ( cin >> value ) {
sum += value; ++numberProcessed; }
double average = sum / numberProcessed ; cout << "Average: " << average << endl;
What if list is empty? The value of the input operation corresponds to
true only if a successful extraction was made
Even Better Way of Averaging
int numberProcessed = 0; double sum = 0;
double value;
while ( cin >> value ) {
sum += value; ++numberProcessed; }
if ( numberProcessed > 0 ) {
double average = sum / numberProcessed ; cout << "Average: " << average << endl; }
else {
cout << "No list to average" << endl; }
The For Statement
Syntaxfor (ForInit; ForExpression; PostExpression)
Action Example
for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; }
ForExpr Action true false ForInit PostExpr Evaluated once at the beginning of the for statements's
execution evaluated at theThe ForExpr is start of each iteration of the loop If ForExpr is true, Action is executed After the Action
has completed, the PostExpression is evaluated If ForExpr is false, program execution continues with next statement
After evaluating the PostExpression, the next iteration of the loop starts
Execution Trace
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl; }
cout << "all done" << endl;
Execution Trace
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl; }
cout << "all done" << endl;
i 0
Execution Trace
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
Execution Trace
for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0
i 0
Execution Trace
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl; }
cout << "all done" << endl;
i is 0
Execution Trace
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl; }
cout << "all done" << endl;
i 1
Execution Trace
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0 i is 1
Execution Trace
for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl;
}
cout << "all done" << endl;
i is 0 i is 1
i 1
Execution Trace
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl; }
cout << "all done" << endl;
i is 0 i is 1
Execution Trace
for (int i = 0; i < 3; ++i) {
cout << "i is " << i << endl; }
cout << "all done" << endl;
i is 0 i is 1
i 2
Execution Trace
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
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
i 2
Execution Trace
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
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
i 3
Execution Trace
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;
cout << "i" << "\t\t" << "2**i" << endl;
for (int i = 0; i <= TableSize; ++i) { cout << i << "\t\t" << Entry << endl; Entry *= 2;
}
Table Revisiting
const int TableSize = 20;
long Entry = 1;
cout << "i" << "\t\t" << "2**i" << endl;
for (int i = 0; i < TableSize; ++i) { cout << i << "\t\t" << Entry << endl; Entry = 2 * Entry;
}
cout << "i is" << i << endl; // illegal
Displaying a Diagonal
SimpleWindow W("One diagonal", 5.5, 2.25); W.Open();
for (int j = 1; j <= 3; ++j) {
float x = j * 0.75 + 0.25; float y = j * 0.75 - 0.25; float Side = 0.4;
RectangleShape S(W, x, y, Blue, Side, Side); S.Draw();
}
Displaying Three Diagonals
SimpleWindow W("Three diagonals", 6.5, 2.25); W.Open();
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
float x = i - 1 + j * 0.75 + 0.25; float y = j * 0.75 - 0.25;
float Side = 0.4;
RectangleShape S(W, x, y, Blue, Side, Side); S.Draw();
}
} The scope of i includes the inner loop.
The scope of j is just the inner loop.
int Counter1 = 0; int Counter2 = 0; int Counter3 = 0; int Counter4 = 0; int Counter5 = 0; ++Counter1;
for (int i = 1; i <= 10; ++i) {
++Counter2; for (int j = 1; j <= 20; ++j) { ++Counter3; } ++Counter4; } ++Counter5;
cout << Counter1 << " " << Counter2 << " "
<< Counter3 << " " << Counter4 << " "
<< Counter5 << endl;
For Into While
Observation The for statement is equivalent to