Title: Operations and Expressions
1Operations and Expressions
2Objectives
- Further work with Object-Centered Design
- Detailed look at numeric types
- Work with bool expressions
- Consider the processing of characters
- Study assignment operator
- Use increment, decrement operators
- First look at class constructors
3Expressions
- Definition any sequence of objects and
operations that combine to produce a value (of a
type) is called an expression. - Exampledouble pressure ((depth /
FEET_PER_ATM) 1) - LBS_PER_SQ_IN_PER_ATM
4Numeric Expressions
- C provides four familiar arithmetic operators
- for performing addition
- - for performing subtraction
- for performing multiplication
- / for performing division
- Each of these four can be applied to either real
(double) or integer (int) operands (Literal,
variable, constant, expression etc).
5Division
- Division behaves differently for int and double
operands - Note the results of the following
- 3/4 0 3.0/4.0 0.75
- 3.0/4 0.75 3/4.0 0.75
- If both operands are integers
- Integer division performed
- Otherwise real division performed
6Integer vs. Real Division
- Recall division from grade school.
Teacher 4 goes into 3 how many
times? Pupils 0 times with a remainder 4 - The expression 3 / 4 returns the quotient.
- This is integer division
- The expression 3 4 returns the remainder (how
about 3(-4) ?). - This is read, "3 mod 4"
7Type Conversions
- Combining an int and a real in the same
expression - 2 3.0 ? 5.0
- C automatically converts narrow values into
wider values - An integer is converted to a real
- Result of the expression is a real
- Often called "promotion"
8Precedence
- Consider the possible value of the expression
- 2 3 4 (2 3) 4
24 or 2 (3 4) 14 ? - Operator precedence governs evaluation order.
- has higher precedence than
- is applied first (when ( and ) are not
involved)
9Operator Precedence
- (), (), , . , -gt (left) HIGHER
- , -,!(NOT) unary (right)
- , /, binary(left)
- ,-
- lt, lt, gt, gt
- , !
-
-
LOWER - See Appendix C for a complete list...
10Associativity
- Consider the possible value of the expression
- 8 - 4 - 2
- (8 - 4) - 2 4
- or 8 - (4 - 2) 6 ?
- Precedence doesnt help us
- Associativity tells us.
- Subtraction is left-associative, the left - is
evaluated first, giving us 4. - Most (but not all) C operators associate left.
- See Appendix C in the text for a complete list...
11Numeric Functions
- The library ltcmathgt contains a variety of
mathematical functions, including - sin(x) asin(x)
- cos(x) acos(x)
- tan(x) atan(x)
- sqrt(x) log10(x)
- log(x) pow(x, y)
- floor(x) ceiling(x)
- abs(x)
-
12Using ltcmathgt functions
- include ltiostreamgt
- include ltcmathgt
- using namespace std
- int main()
-
- cout ltlt \nEnter base and exponent
- double base, exponent
- cin gtgt base gtgt exponent
- double result pow(base, exponent)
- cout ltlt base ltlt raised to the power
- ltlt exponent ltlt is ltlt result ltlt endl
13Type Conversions
- Possible to explicitly convert a value from one
type to another - Syntax to usetype (expression) or (type)
expression - Conversion can cause loss of datadouble x
3.456cout ltlt (int) x
What gets output?
14Boolean Expressions
- C type bool has two literals
- false and true
- Relational operators produce boolean expressions
(char, integer, real)
15Relational Operations
- Use operators for comparisons
- Each takes two operands
- Produces a bool value (true or false)
- x y x ! y
- x lt y x gt y
- x gt y x lt y
- Warning
- Do NOT confuse (assignment)
- With (equality).
- 3ltxlt6 is NO GOOD
16Compound Boolean Expressions
17Compound Boolean Expressions
- More complex boolean expressions can be built
using the logical operators - a b // true iff a, b are both true
- a b // true iff a or b is true
- !a // true iff a is false
- Example
- cin gtgt score
- assert (0 lt score score lt 100)
18Short-Circuit Evaluation
- Consider the boolean expression( n ! 0 ) ( x
lt 1.0 / n ) - If n 0 the right hand expression causes a
program crash - C will evaluate the original expression from
left to right - If n 0, the left expression evaluates false
- Since it is an , this makes the whole
expression false - Thus it does not proceed to the right expression
19Preconditions
- Definition When a program makes assumptions
about its input values - Example that theyre positive
- Preconditions are boolean expressions
- Must be true in order for the program to work
correctly. - To check preconditions, C provides the assert()
mechanism...
20Assertions
- include ltiostreamgt
- include ltcassertgt
- using namespace std
- int main()
-
- cout ltlt \nEnter your age
- int age
- cin gtgt age
- assert(age gt 0)
- // ...
-
21Character Expressions
- Character variables can be
- Declared and initialized
- char middleInitial 'Q'
- Assigned
- middleInitial 'Z'
- Used for I/O
- cout ltlt middleInitial
- cin gtgt middleInitial
- Compared
- assert (middleInitial ! 'X')
22Character Functions
- Boolean character-processing functions found in
ltctypegt library - isalpha(ch) isalnum(ch)
- isdigit(ch) iscntrl(ch)
- islower(ch) isupper(ch)
- isspace(ch) ispunct(ch)
- isprint(ch) isgraph(ch)
- Case-conversion functions
- toupper(ch) tolower(ch)
23Assignment expression vs statement
- Syntaxvariable expression ()
- Expression is evaluated
- Value placed in memory location associated with
variable - Note Left side must be a variable, and the type
of the right side must compatible to the
variables type - ExamplexCoord 4.56code 'T'
24Assignment
- Given the sequence of three assignment
statements, note the results - Note that previous variable values are gone after
execution of assignment
25Assignment
- The assignment operator
- Right-associative,
- Supports expressions like
- int w, x, y, z
- w x y z 0
- The rightmost is applied first,
- assigning z zero,
- then y is assigned the value of z (0),
- then x is assigned the value of y (0)
- finally w is assigned the value of x (0).
26Assignment Shortcuts
- Some assignments are so common
- var var x // add x to var
- var var - y // sub y from var
- C provides shortcuts for them
- var x // add x to var
- var - y // sub y from var
27In General
- Most arithmetic expressions of the form
- var var D value
- can be written in the shortcut form
- var D value
- Examples
- double x, y
- cin gtgt x gtgt y
- x 2.0 // double xs value
- y / 2.0 // decrease y by half
28Increment and Decrement
- Other common assignments include
- var var 1 // add 1 to var
- var var - 1 // sub 1 from var
- C provides shortcuts for them, too
- var // add 1 to var
- var-- // sub 1 from var
29Prefix Increment
- The prefix form of increment produces the final
(incremented) value as its result - int x, y 0
- x y
- cout ltlt x // 1 is displayed
- The prefix decrement behaves similarly...
30Postfix Increment
- The postfix form of increment produces the
original (unincremented) value as its result - int x, y 0
- x y
- cout ltlt x // 0 is displayed
- // y now holds value of 1
- The prefix decrement behaves similarly...
31Prefix vs. Postfix
- So long as the increment (or decrement) operator
is used as a separate statement - int y 0, x 0
- x // x 1
- y // y 1
- it makes no difference which version is used.
32Expressions into Statements Semicolons
- An expression followed by a semicolon becomes an
expression statement - x y z
- 'A'
- cos (z)
33I/O Streams
- C has no I/O as part of the language
- I/O streams are provided by istream and ostream
34Input Expressions
- Form
- input_stream gtgt variable
- May be chained togethercin gtgt x gtgt y
- Adapts to whatever type variable is
- User must enter correct type
- Best to prompt user for input expected
- cout ltlt "Enter choice (1 10) "
35Output Expressions
- Form
- output_stream ltlt expression
- May be chained
- cout ltlt "The sum " ltlt sum
- The expression can be a variable, a constant or a
combination using operators - cout ltlt "Sum " ltlt v1 v2 v3
- The expression adapts to whatever types are used
36Output Formatting
- Possible to specify appearance of output
- From iostream(for your reference)
- showpoint Display decimal point and trailing
zeros for all real numbers. - noshowpoint Hide decimal point and trailing
zeros for whole real numbers (default). - fixed Use fixed-point notation for real values.
- scientific Use scientific notation for real
values. - boolalpha Display boolean values as strings
true and false. - left Display values left justified within a
field. - right Display values right justified within a
field (default). - From iomanip(will be used in this semester)
- setw(w) Display the next value in a field of
size w (default 1). - setprecision(p) Display p fractional digits for
all subsequent output of real values (common
default is 6).
Must specify the proper include files to use
these. include ltiostreamgtinclude
ltiomanipgtusing namespace std
37Objected-Centered Design
- Problem
- A manufacturing company uses trucks for delivery.
For each trip, the driver records mileage,
gallons of fuel, cost of fuel, etc. - The accountants want a report for miles per
gallon, total trip cost, cost per mile. - The controller wants a program to assist in
recording and calculating these statistics
38Behavior
For trip statisticsEnter miles traveled
99Enter gallons fuel 99.99Enter cost per
gallon 99.99Enter per mile cost for this
truck 9.99 Mileage for this trip 99.99Total
trip cost 99.99Trip cost per mile 99.99
39Objects
Description Software Objects Software Objects Software Objects
Description Type Kind Name
screen ostream variable cout
total miles traveled double variable miles
total gallons used double variable gallonsOfFuel
fuel cost per gallon double variable unitFuelCost
operating cost/mi double variable unitOperatingCost
keyboard istream variable cin
miles per gallon double variable milesPerGallon
total cost of trip double variable totalTripCost
cost per mile double variable costPerMile
40Operations
- Display prompt on screen for input
- Read sequence of four reals from keyboard
- Compute mpg
- divide miles by number of gallons
- Compute total cost of trip add ..
- cost of fuel gallons price / gallon
- operating costs miles cost / mile
- Compute cost of trip per mile
- Divide total cost by number of miles traveled
- Output real values
41Algorithm
- 1. Display a prompt via cout for miles,
gallonsOfFuel, unitFuelCost, and
unitOperatingCost. - 2. Read values from cin into miles,
gallonsOfFuel, unitFuelCost, and
unitOperatingCost. - 3. Check that each of these values is positive.
- 4. Compute milesPerGallon miles /
gallonsOfFuel. - 5. Compute fuelCost gallonsOfFuel
unitFuelCost. - 6. Compute operatingCost unitOperatingCost
miles. - 7. Compute totalTripCost fuelCost
operatingCost. - 8. Compute costPerMile totalTripCost / miles.
- 9. Via cout, display milesPerGallon,
totalTripCost and costPerMile, with descriptive
labels.
42Coding, Execution, Testing
- View source code Figure 3.2
- Note use of
- prompting
- input expressions
- formatting of output
- View sample runs